这两天对java并发的内容进行了一个学习,主要是对synchronized和volatile这两个关键字做了更深入的学习。由此想到怎样创建线程安全的单例模式,网上有很多,写下来是加深自己的理解!!!
package com.ab.adou.thread;
/**
* @author ASUS
* 多线程情况下 安全的线程模式
* double click check 双检查锁机制
*/
public class SafeThreadSingleton {
private volatile static SafeThreadSingleton instance ;
private SafeThreadSingleton(){}
public static SafeThreadSingleton getInstance(){
if (instance == null) {
synchronized (SafeThreadSingleton.class) {//加锁 防止同时有多个线程进入 并new对象
if(instance == null){//这里加一重判断 是防止在外面等待锁的线程 又去new对象
instance = new SafeThreadSingleton();
}
}
}
return instance;
}
}
—————————————这里是华丽的分割线————————————-
package com.ab.adou.thread;
public class MyCheckThread extends Thread{
@Override
public void run() {
System.out.println(SafeThreadSingleton.getInstance().hashCode());
}
public static void main(String[] args) {
MyCheckThread[] mts = new MyCheckThread[100];
for(int i = 0 ; i < mts.length ; i++){
mts[i] = new MyCheckThread();
}
for (int j = 0; j < mts.length; j++) {
mts[j].start();
}
}
}
主要是想说明一下 为什么要进行第二次的instance == null判断,因为synchronized是把锁加在了类class上,有可能有多个线程在等待第一个获取锁的线程创建完实例后释放锁,如果不进行二次判断,这些等待锁的线程又会继续创建出新的实例来,违背我们的初衷。