贴出一篇我参考的文章:http://blog.csdn.net/cselmu9/article/details/51366946
这里补充一下就是下面的单例为什么是线程不安全的:
public class Singleton1 {
private static Singleton1 instance = null;
private Singleton1(){
}
// 唯一实例对象方法
public static Singleton1 getInstance(){
if(instance == null){
instance = new Singleton1();
}
return instance;
}
public static void main(String[] args) throws InterruptedException{
Thread ts[] = new Thread[2];
for(int i = 0; i < 2; i++){
ts[i] = new Thread(){
@Override
public void run() {
// dosomething
Singleton1 s = Singleton1.getInstance();
System.out.println(s.hashCode());
}
};
}
for(int i = 0; i < 2; i++){
ts[i].start();
}
}
}
结果:
714682869
798941612
原因就是高并发下可能同时获取instance,发现instance == null,然后同时都实例化了,所以线程不安全。
我们改一下:
for(int i = 0; i < 2; i++){
ts[i].start();
Thread.sleep(1000);
}
结果:
1701381926
1701381926
发现线程安全了,原因就是我们让第二个线程晚点运行,第一个运行好了再运行,这样第二个线程获取instance就不是null了,不会重新实例化。