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();
        }
    }
    

      两个判断的位置

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

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

    输出结果:

  • 相关阅读:
    03 Logistic Regression
    01 Linear Regression with One Variable
    00 Introduction
    virsh使用
    Linux配置输入设备(如停用笔记本键盘)
    linux安装ipconfig等网络工具
    软件工程团队第五次作业
    团队第四次作业
    软件工程团队第三次作业
    软件工程团队第二次作业
  • 原文地址:https://www.cnblogs.com/qfxydtk/p/8728937.html
Copyright © 2011-2022 走看看