多线程下懒汉单例的问题

老规矩,看例子

public class LazySingleton {
    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                Singleton.getInstance();
            }
        };
        for (int i = 0; i < 20; i++) {
            Thread thread = new Thread(runnable);
            thread.start();
        }   
    }
}

class Singleton{
    private static Singleton instance = null;
    public Singleton(){
        System.out.println("实例化了一个对象");
    }
    public static Singleton getInstance(){
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}
image.png

你变了!!!这不是我要的单例!!!

这是因为:
我们先假设第一个线程成功执行了这段代码。
if (instance == null)
与此同时第x个线程,可能是5678910...抢到了cpu资源并执行了
if (instance == null)
此时,第一个线程和第x个线程都通过了条件判断,当他们得到cpu资源后继续执行下面的代码,因此会创建出多个实例。

怎么办?怎么让它回心转意?

public static synchronized Singleton getInstance(){
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }

在getInstance()方法上加个同步锁就好啦,修改后的运行结果:


image.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容