zoukankan      html  css  js  c++  java
  • 单例模式之懒汉模式,懒汉模式之高效模式,DLC双判断模式

    import java.util.concurrent.LinkedBlockingQueue;
    import java.util.concurrent.ThreadPoolExecutor;
    import java.util.concurrent.TimeUnit;
    
    /**
     * 单例模式之懒汉模式
     * 懒汉模式之高效模式
     * DLC双判断模式
     */
    public class SingleClassLazySync {
        private static SingleClassLazySync singleClassLazySync;
    
        private SingleClassLazySync() {
        }
    
        public static SingleClassLazySync getInstance() {
            if (singleClassLazySync == null) {
                synchronized (SingleClassLazySync.class) {
                    if (singleClassLazySync == null) {
                        System.out.println("i m in new instance!");
                        singleClassLazySync = new SingleClassLazySync();
                    }
                }
            }
            return singleClassLazySync;
        }
    
        static class A implements Runnable {
    
            @Override
            public void run() {
                System.out.println(SingleClassLazySync.getInstance().hashCode());
            }
        }
    
        public static void main(String[] args) {
            ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 5, 0l, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
            boolean flag = true;
            for (int i = 0; i < 5; i++)
                executor.execute(new A());
            executor.shutdown();
        }
    }
    

      两个判断的位置

    第一个为了日后获取实例的线程准备

    第二个为了刚刚获得锁的线程准备,如果没有这个,将会有同步问题。

    输出结果:

  • 相关阅读:
    Python3---常见函数---super()
    Python3---常见函数---type()
    Python3---面对对象
    Python3---BeautifulSoup---节点选择器
    Python3---Beautiful Soup
    0X01应用程序黑客技术
    Python3---标准库---re
    (trie) UVA
    (trie)UVALive
    (平方分割)POJ 2104 K-th Number
  • 原文地址:https://www.cnblogs.com/qfxydtk/p/8728937.html
Copyright © 2011-2022 走看看