1. 程式人生 > >10.併發程式設計--單例模式(飢餓模式-懶漢模式)

10.併發程式設計--單例模式(飢餓模式-懶漢模式)

併發程式設計--單例模式(飢餓模式-懶漢模式)

1. 單例模式:

- 最常見的單例模式:飢餓模式-懶漢模式;

  • 1. 飢餓模式:直接例項化物件;
  • 2. 懶漢模式:呼叫方法時進行例項化物件。

- 還有一種經典做法:在多執行緒模式中,一般選擇如下幾種單例模式:

  • 1. dubble check instance:
  • 2. static inner class:

示例:Singletion.java --> static inner class:

 1 public class Singletion {
 2 
 3     private static
class InnerSingletion { 4 private static Singletion single = new Singletion(); 5 } 6 7 public static Singletion getInstance(){ 8 return InnerSingletion.single; 9 } 10 }

示例:  dubble check instance:

 1 public class DubbleSingleton {
 2 
 3 private static DubbleSingleton ds;
4 5 public static DubbleSingleton getDs(){ 6 if(ds == null){ 7 try { 8 //模擬初始化物件的準備時間... 9 Thread.sleep(3000); 10 } catch (InterruptedException e) { 11 e.printStackTrace(); 12 } 13 synchronized (DubbleSingleton.class) { 14 if
(ds == null){ 15 ds = new DubbleSingleton(); 16 } 17 } 18 } 19 return ds; 20 } 21 22 public static void main(String[] args) { 23 Thread t1 = new Thread(new Runnable() { 24 @Override 25 public void run() { 26 System.out.println(DubbleSingleton.getDs().hashCode()); 27 } 28 },"t1"); 29 Thread t2 = new Thread(new Runnable() { 30 @Override 31 public void run() { 32 System.out.println(DubbleSingleton.getDs().hashCode()); 33 } 34 },"t2"); 35 Thread t3 = new Thread(new Runnable() { 36 @Override 37 public void run() { 38 System.out.println(DubbleSingleton.getDs().hashCode()); 39 } 40 },"t3"); 41 42 t1.start(); 43 t2.start(); 44 t3.start(); 45 } 46 }