单例模式中的懒汉式线程安全

在单例模式中分为懒汉式和饿汉式,其中饿汉式是线程安全的,要实现懒汉式线程安全要做双重的判断,其中代码如下:

public static Singleton2 getInstance(){
            if(instance == null) {
            synchronized (Singleton2.class){
                if (instance == null){
                    instance = new Singleton2();
                }
            }
        }
        return instance;
    }

分析:当A线程判断instance为null时,CPU的资源被B抢占,然后执行同步方法,获得instance实例,这时A获得CPU资源,因为B已经将共享资源的实例化了,所以再次判断时是不为null的,因此是线程安全的。

猜你喜欢

转载自blog.csdn.net/ocean_java666/article/details/80643059