Lazy singleton pattern of multi-threading

/**
 * 1. 懒汉(延迟加载)
 * 2. 正确
 * 3. 效率还比较高
 * 通过
 * 1. volatile 的引入,目的解决 ins = new ...(); 重排序带来的问题
 * 2. synchronized 的引入,目的是解决原子性问题
 * 3. 见方法注释
 */
public class LazySingleton3 {
//直属类的对象
    private static volatile LazySingleton3 ins = null;
 //构造方法
    private LazySingleton3() {}
   //一个获得  ins 的方法 
    public static LazySingleton3 getInstance3() {
        if (ins == null) {
            synchronized (LazySingleton3.class) {
                if (ins == null) {
                    ins = new LazySingleton3(); 
                }
            }
        }

        return ins;
    }
 //建立一个线程的类
    static class MyThread extends Thread {
        @Override
        public void run() {
            LazySingleton3 ins1 = LazySingleton3.getInstance3();
            System.out.println(ins1);
        }
    }
//将这个程序以多线程运行
    public static void main(String[] args) {
        MyThread[] threads = new MyThread[20];
        for (int i = 0; i < 20; i++) {
            threads[i] = new MyThread();
        }
        for (int i = 0; i < 20; i++) {
            threads[i].start();
        }
        /*
        单例模式之懒汉1 ins1 = 单例模式之懒汉1.getInstance();
        单例模式之懒汉1 ins2 = 单例模式之懒汉1.getInstance();
        单例模式之懒汉1 ins3 = 单例模式之懒汉1.getInstance();

        System.out.println(ins1 == ins2);
        System.out.println(ins2 == ins3);
        */
    }
}

Lazyのsingleton pattern:
Single Example: only instantiate an object.

And starving start initializes different, lazy initialization will only be called when there is an object in the thread, the purpose of the move is to save memory space.

Not guarantee atomicity problem would exist if not synchronized, a plurality of objects may be new, non-compliance single embodiment.
If there is no outside if (ins == null), it will cause the entire code is less efficient, because after the first new objects, the thread mutually exclusive lock will still be robbed.
If there is no pre-volatile global variables ins, then ins (reference assignment open space, initialization, to) three major steps have reordered this issue inside the object.

Published 15 original articles · won praise 0 · Views 261

Guess you like

Origin blog.csdn.net/rushrush1/article/details/104849828