public class MySingleton {
private static MySingleton instance = null;
private MySingleton (){}
//synchronized加载在方法上,效率不高.所以synchronized只作用关键代码
public static MySingletongetInstance() {
if(instance == null){
//此处作为同步关键字的阻塞点
synchronized (MySingleton.class) {
//阻塞之后必须使用二次判断,避免类已经被某个线程实例化,但是其他线程过了判断。
if(null == instance){
instance = new MySingleton();
}
}
}
return instance;
}
}
看了个帖子,这是最后总结。
原贴地址:https://blog.youkuaiyun.com/Tian779278804/article/details/76058586