码迷,mamicode.com
首页 > 其他好文 > 详细

单例模式 懒汉模式

时间:2016-10-07 01:50:24      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

懒汉模式线程不安全:

package com.ddy.singleton;
public class Singleton {
private static Singleton instance;
private Singleton(){
}
public static Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}

 

package com.ddy.singleton;
public class Service1 implements Runnable {
private Singleton singleton = null;
//public Set<Singleton> singles = new HashSet<>();  
@Override
public void run() {
// TODO Auto-generated method stub
singleton = Singleton.getInstance();
System.out.println(singleton+","+Thread.currentThread().getName());
}
}

 

package com.ddy.singleton;
public class Test {
public static void main(String[] args) throws InterruptedException {
Service1 t1 = new Service1();
Service1 t2 = new Service1();
new Thread(t1).start();
new Thread(t2).start();
}
}

 

输出结果不一致 ,说明线程不安全

修改如下:

package com.ddy.singleton;
public class Singleton {
private static Singleton instance;
private Singleton(){
}
public static Singleton getInstance(){
if(instance == null){
synchronized (Singleton.class){
if (instance == null) {                 //Double Checked
               instance = new Singleton();
           }
}
}
return instance;
}
}
这样就做到线程安全了

 

单例模式 懒汉模式

标签:

原文地址:http://www.cnblogs.com/vincent4code/p/5935295.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!