单例模式中的线程安全问题

xiaoxiao2021-03-01  17

[size=large]教科书中的单例模式的描述好些都没注意线程安全,很两个线程同时去创造实例,这样就能够产生两个实例,正确写法如下: public class Singleton(){ private volatile static Singleton singleton; private Sington(){}; public static Singleton getInstance(){ if(singleton == null){ synchronized (Singleton.class); if(singleton == null){ singleton = new Singleton(); } } } return singleton; } } volatile在jdk 1.5以上才能使用---代码源于《head first设计模式》 http://www.blogjava.net/duduli/archive/2008/11/22/241945.html[/size]
转载请注明原文地址: https://www.6miu.com/read-3450127.html

最新回复(0)