1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public class Singleton{ private volatile static Singleton uniqueInstance; private Singleton(){} public static Singleton getUniqueInstance(){ //先判断对象是否已经实例化过才进行加锁代码 if(uniqueInstance == null){ synchronized(Singleton.class){ if(uniqueInstance == null){ uniqueInstance = new Singleton(); } } } return uniqueInstance; } }
|
使用volatile可以禁止JVM的指令重排,保证多线程环境下也能正常运行。