懶漢模式 餓漢模式 執行緒池例項

2021-08-28 17:25:32 字數 2578 閱讀 9074

單例設計模式:保證類在記憶體中只有乙個物件

//餓漢式

class singleton

//2,宣告乙個引用

private static singleton s = new singleton();

//3,對外提供公共的訪問方法

public static singleton getinstance()

}//懶漢式

class singleton

//2,宣告乙個引用

private static singleton s ;

//3,對外提供公共的訪問方法

public static singleton getinstance()

return s;

}}singleton s1 = singleton.s;                //成員變數被私有,不能通過類名.呼叫

singleton s1 = singleton.getinstance();

餓漢式和懶漢式的區別

* 1,餓漢式是空間換時間,懶漢式是時間換空間

* 2,在多執行緒訪問時,餓漢式不會建立多個物件,而懶漢式有可能會建立多個物件

單例設計模式的應用

runtime r = runtime.getruntime();        //獲取執行時物件

r.exec("shutdown -s -t 300");            //設定電腦300秒後關機    

r.exec("shutdown -a");                //取消關機計畫

timer t = new timer();                //計時器

//第乙個引數,是安排的任務,第二個引數是執行的時間,第三個引數是過多長時間再重複執行

t.schedule(new mytimertask(), new date(118, 9, 4, 15, 57, 50),3000);

class mytimertask extends timertask

}synchronized(this)

reentrantlock r = new reentrantlock();

condition c1 = r.newcondition();

condition c2 = r.newcondition();

condition c3 = r.newcondition();

r.lock();                    //獲取鎖

r.unlock();                    //釋放鎖

c1.await();                    //c1執行緒等待

c2.await();                    //c2執行緒等待

c3.await();                    //c3執行緒等待

c1.signal();                    //即將執行c1執行緒

c2.signal();                    //即將執行c2執行緒

c3.signal();                    //即將執行c3執行緒

threadgroup tg = new threadgroup("我是乙個新的執行緒組");        //建立新的執行緒組

myrunnable mr = new myrunnable();                //建立runnable的子類物件    

thread t1 = new thread(tg, mr, "張三");                //將執行緒t1放在組中

thread t2 = new thread(tg, mr, "李四");                //將執行緒t2放在組中

t1.getthreadgroup().getname();                    //獲取組名

class myrunnable implements runnable

}executorservice pool = executors.newfixedthreadpool(2);    //建立執行緒池

pool.submit(new myrunnable());                //將執行緒放進池子裡並執行

pool.submit(new myrunnable());        

pool.shutdown();                    //關閉執行緒池

executorservice pool = executors.newfixedthreadpool(1);    //建立執行緒池

futuref1 = pool.submit(new mycallable(100));    //將執行緒放進池子裡並執行

f1.get();                        //獲取call()計算結果

class mycallable implements callable    

public integer call() throws exception         

return sum;

}}

餓漢模式和懶漢模式

package pattern.singleton 餓漢式單例類.在類初始化時,已經自行例項化 public class singleton1 已經自行例項化 private static final singleton1 single new singleton1 靜態工廠方法 public st...

懶漢模式與餓漢模式

懶漢模式 加截類的時候就建立物件 class single private static single s new single pubic static single getinstance 餓漢模式 呼叫getinstance 方法時才建立物件 class single private stat...

餓漢模式vs懶漢模式

餓漢式 建立物件例項的時候直接初始化 空間換時間 public class singletonone 2 建立該型別的私有靜態例項 private static singletonone instance newsingletonone 3 建立公有靜態方法返回靜態例項物件 public stati...