多线程情况下,单例模式的实现方式

方式1(推荐)

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

 

方式2(double check)

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

 


posted @ 2018-05-18 09:45  无名草110  阅读(433)  评论(0编辑  收藏  举报