可见性volatile的使用:
volatile boolean inited = false;
// 线程1
comtext = loadContext();
inited = true;
//线程2
while(!inited){
sleep();
}
doSomethingConfig(context);
懒汉式和饿汉试:
// 懒汉
public class SingletonException1 {
// 私有化构造
private SingletonException1() {
}
// 单例对象
private static SingletonException1 singletonException1 = null;
// 静态工厂方法
public static SingletonException1 getSingletonException1(){
if(singletonException1 == null){
singletonException1 = new SingletonException1();
}
return singletonException1;
}
}
// 饿汉
public class SingletonException2 {
// 私有构造
private SingletonException2(){}
private static SingletonException2 singletonException2 = new SingletonException2();
private static SingletonException2 getSingletonException2 (){
return singletonException2;
}
}
为了让懒汉式保证线程安全使用synchronized,只能让一个线程使用,降低了线程的效率,不推荐
// 静态工厂方法
public static synchronized SingletonException1 getSingletonException1(){
if(singletonException1 == null){
singletonException1 = new SingletonException1();
}
return singletonException1;
}
提高效率进行修改,只锁本类。呢么进行改进
// 静态工厂方法
public static SingletonException1 getSingletonException1(){
if(singletonException1 == null){
// 双层检测机制和锁
synchronized (SingletonException1.class) {
if(singletonException1 == null){
singletonException1 = new SingletonException1();
}
}
}
return singletonException1;
}
这样线程就安全了吗?cpu和jvm发生指令重排。
再进行改进:
如果一个共享变量(类的成员变量、类的静态成员变量)被volatile修饰之后,那么就具备了两层语义:
1)保证了不同线程对这个变量进行操作时的可见性,即一个线程修改了某个变量的值,这新值对其他线程来说是立即可见的。
2)禁止进行指令重排序。
// 私有化构造
private SingletonException1() {
}
// 单例对象
private volatile static SingletonException1 singletonException1 = null;
// 静态工厂方法
public static SingletonException1 getSingletonException1(){
if(singletonException1 == null){
// 双层检测机制和锁
synchronized (SingletonException1.class) {
if(singletonException1 == null){
singletonException1 = new SingletonException1();
}
}
}
return singletonException1;
}
ThreadPoolExecutor