单例问题与线程安全性

饿汉式

  没有线程安全问题

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

}

猜你喜欢

转载自www.cnblogs.com/quyangyang/p/10366743.html