zoukankan      html  css  js  c++  java
  • 线程安全的两种单例模式

    两种常见的单例模式

    静态内部类单例模式

    /*
     *  静态内部类单例模式
     */
    public class Singleton {
        private Singleton() {
        }
    
        private static final class SingletonHolder {
            private static final Singleton INSTANCE = new Singleton();
        }
    
        public static Singleton getInstance() {
            return SingletonHolder.INSTANCE;
        }
    
        public static void main(String[] args) {
            Thread t1 = new Thread(new Runnable() {
    
                @Override
                public void run() {
                    System.out.println(Singleton.getInstance().hashCode());
                }
    
            }, "t1");
    
            Thread t2 = new Thread(new Runnable() {
    
                @Override
                public void run() {
                    System.out.println(Singleton.getInstance().hashCode());
                }
    
            }, "t2");
    
            Thread t3 = new Thread(new Runnable() {
    
                @Override
                public void run() {
                    System.out.println(Singleton.getInstance().hashCode());
                }
    
            }, "t3");
    
            t1.start();
            t2.start();
            t3.start();
        }
    }
    
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class InnerSingleton {
        private InnerSingleton() {
        }
    
        private static final class InnerSingletonHandle {
            private static final InnerSingleton INSTANCE = new InnerSingleton();
        }
    
        public static InnerSingleton getInstance() {
            return InnerSingletonHandle.INSTANCE;
        }
    
        public static void main(String[] args) {
            int num = 10;
            ExecutorService executorService = Executors.newCachedThreadPool();
    
            for (int i = 0; i < num; i++) {
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println(Thread.currentThread().getName() + ":	" + InnerSingleton.getInstance().hashCode());
                    }
                });
            }
            executorService.shutdown();
        }
    }
    

    运行结果

    ``` pool-1-thread-1: 991873903 pool-1-thread-2: 991873903 pool-1-thread-3: 991873903 pool-1-thread-4: 991873903 pool-1-thread-6: 991873903 pool-1-thread-7: 991873903 pool-1-thread-8: 991873903 pool-1-thread-10: 991873903 pool-1-thread-5: 991873903 pool-1-thread-9: 991873903

    Process finished with exit code 0

    </div>
    
    ### 双重校验单例模式
    ```java
    /*
     * 双重校验单例模式
     */
    public class Singleton {
        private static volatile Singleton instance;
    
        private Singleton() {
        }
    
        public static Singleton getInstance() {
            if (instance == null) {
                synchronized (Singleton.class) {
                    if (instance == null) {
                        instance = new Singleton();
                    }
                    // instance = new Singleton();
                }
            }
            return instance;
        }
    
        public static void main(String[] args) {
            Thread t1 = new Thread(new Runnable() {
    
                @Override
                public void run() {
                    System.out.println(Singleton.getInstance().hashCode());
                }
    
            }, "t1");
    
            Thread t2 = new Thread(new Runnable() {
    
                @Override
                public void run() {
                    System.out.println(Singleton.getInstance().hashCode());
                }
    
            }, "t2");
    
            Thread t3 = new Thread(new Runnable() {
    
                @Override
                public void run() {
                    System.out.println(Singleton.getInstance().hashCode());
                }
    
            }, "t3");
    
            t1.start();
            t2.start();
            t3.start();
        }
    }
    
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class DoubleCheckSingleton {
        private DoubleCheckSingleton() {
        }
    
        private static volatile DoubleCheckSingleton INSTANCE;
    
        public static DoubleCheckSingleton getInstance() {
            if (INSTANCE == null) {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (DoubleCheckSingleton.class) {
                    if (INSTANCE == null) {
                        INSTANCE = new DoubleCheckSingleton();
                    }
                    // INSTANCE = new DoubleCheckSingleton();
                }
            }
            return INSTANCE;
        }
    
        public static void main(String[] args) {
            int num = 10;
            ExecutorService executorService = Executors.newCachedThreadPool();
    
            for (int i = 0; i < num; i++) {
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println(Thread.currentThread().getName() + ":	" + DoubleCheckSingleton.getInstance().hashCode());
                    }
                });
            }
            executorService.shutdown();
        }
    }
    

    运行结果

    ``` pool-1-thread-1: 405652733 pool-1-thread-4: 405652733 pool-1-thread-7: 405652733 pool-1-thread-2: 405652733 pool-1-thread-6: 405652733 pool-1-thread-5: 405652733 pool-1-thread-3: 405652733 pool-1-thread-8: 405652733 pool-1-thread-9: 405652733 pool-1-thread-10: 405652733

    Process finished with exit code 0

    </div>
    
    ### 最后总结
    ![](https://img2018.cnblogs.com/blog/1306719/201811/1306719-20181107155022590-664214116.png)
    ![](https://img2018.cnblogs.com/blog/1306719/201811/1306719-20181107155028084-1715481635.png)
  • 相关阅读:
    【转】IBatis.Net项目数据库SqlServer迁移至Oracle
    【转】远程桌面 剪切板复制文件失效解决方法
    为什么越学反而越蠢?碎片化学习是个骗局
    Spring MVC起步
    [1-1] 把时间当做朋友(李笑来)Chapter 1 【心智的力量】 摘录
    Java反射总结
    No enclosing instance of type Demo is accessible. Must qualify the allocation with an enclosing instance of type Demo (e.g. x.new A() where x is an instance of Demo).
    hiberbnate 缓存策略概述
    一分钟看你缺乏哪种维生素
    zrrx笔试题(一)——文件复制&日期天数差
  • 原文地址:https://www.cnblogs.com/hgnulb/p/9397974.html
Copyright © 2011-2022 走看看