java併發編程--單例&多線程

package cn.bufanli.test.singleton;

/**
 * 單例&多線程
 * 單例模式,最常見的就是飢餓模式和懶漢模式,一個直接實例化對象
 * 一個在調用方法時進行實例化對象,在多線程中,考慮到性能和線程安全問你題,
 * 我們一般選擇下面兩種單例模式,在提高性能的同時,又保證了線程安全
 *  dubble check instance 兩次確認
 *  static inner class 靜態內部類
 */
public class singletonThreadDemo {
}

Dubble check instance 

package cn.bufanli.test.singleton;

public class DubbleSingleton {
    private static DubbleSingleton ds;
    public static DubbleSingleton getDS(){
        if(ds == null){
            try {
                //模擬初始化對象的準備時間..
                Thread.sleep(3000);
            }catch(Exception e){
                e.printStackTrace();
            }
            synchronized (DubbleSingleton.class){
                if(ds == null){
                    ds = new DubbleSingleton();
                }
            }
        }
        return ds;
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            System.out.println(DubbleSingleton.getDS().hashCode());
        },"t1");
        Thread t2 = new Thread(() -> {
            System.out.println(DubbleSingleton.getDS().hashCode());
        },"t2");
        Thread t3 = new Thread(() -> {
            System.out.println(DubbleSingleton.getDS().hashCode());
        },"t3");
        t1.start();
        t2.start();
        t3.start();
    }
}

static inner class

package cn.bufanli.test.singleton;

public class Singleton {
    private static class InnerSingleton{
        private static Singleton single = new Singleton();
    }
    public static Singleton getInstance(){
        return InnerSingleton.single;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章