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

方式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 }

 


转载于:https://www.cnblogs.com/billmiao/p/9872206.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值