zoukankan      html  css  js  c++  java
  • 单例问题与线程安全性

    饿汉式

      没有线程安全问题

    //Singleton.java

    public
    class Singleton { private Singleton() {} private static Singleton instance = new Singleton(); public static Singleton getInstance() { return instance; } }
    public class Main {
        
    public static void main(String[] args) {
        Singleton s1 = Singleton.getInstance();
        Singleton s2 = Singleton.getInstance();
        Singleton s3 = Singleton.getInstance();
        Singleton s4 = Singleton.getInstance();
        
        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s3);
        System.out.println(s4);
    }
    
    }

    懒汉式

      双重检验加锁解决线程安全问题

    public class Singleton2 {
        private Singleton2() {}
        
        private static Singleton2 instance;
    //    
    //    public static synchronized Singleton2 getInstance() {
    //        if(instance == null) {
    //            try {
    //                Thread.sleep(100);
    //            } catch (InterruptedException e) {
    //                // TODO Auto-generated catch block
    //                e.printStackTrace();
    //            }
    //            instance = new Singleton2();
    //        }
    //        return instance;
    //    }
        
        
        /*
         * 双重检查加锁制
         */
        public static Singleton2 getInstance() {
            if(instance == null) {
                synchronized(Singleton.class) {
                    if(instance == null) {
                        instance = new Singleton2();
                    }
                }
            }
            return instance;
        }
        //指令重排序问题
            //申请内存空间
            //在这块空间实例化对象
            //instance的引用指向这块内存空间
    }
    public class MutiThreadMain {
        
        public static  void main(String[] args) {
            
            ExecutorService threadPool = Executors.newFixedThreadPool(20);
            
            for(int i = 0;i<20;i++ ) {
                threadPool.execute(new Runnable() {
    
                    @Override
                    public void run() {
                        System.out.println(Thread.currentThread().getName()+ ":"+Singleton2.getInstance());
                    }
                });
            }
            threadPool.shutdown();
        }
    
    }
  • 相关阅读:
    我的云之旅hadoop集群(3)
    动态域名绑定
    我的云之旅hadoop集群集成Hive(4)
    Axis2实践
    PHP Apache Mysql搭建
    JavaEE程序员必读图书大推
    我的云之旅hadoop集群集成Hbase集群(5)
    本博客总排名进入前100
    关系数据库及NoSql图书大推荐
    Last_IO_Errno: 1032
  • 原文地址:https://www.cnblogs.com/quyangyang/p/10366743.html
Copyright © 2011-2022 走看看