ThreadLocal實現單例模式(6)

1. ThreadLocal單例模式

1. 1 ThreadLocal單例模式實現

/**
 * @author xiyou
 * ThreadLocal 實現單例模式
 */
public class ThreadLocalSingleton {
    private static final ThreadLocal<ThreadLocalSingleton> threadLocalInstanceThreadLocal
            = new ThreadLocal<ThreadLocalSingleton>() {
        @Override
        protected ThreadLocalSingleton initialValue() {
            return new ThreadLocalSingleton();
        }
    };

    private ThreadLocalSingleton() {
    }

    public static ThreadLocalSingleton getInstance() {
        return threadLocalInstanceThreadLocal.get();
    }
}

1.2 測試是否是單例模式:


public static void main(String[] args) {
    ThreadLocalSingleton instance = ThreadLocalSingleton.getInstance();
    System.out.println(Thread.currentThread().getName() + " : " + instance);
    instance = ThreadLocalSingleton.getInstance();
    System.out.println(Thread.currentThread().getName() + " : " + instance);
    instance = ThreadLocalSingleton.getInstance();
    System.out.println(Thread.currentThread().getName() + " : " + instance);
    instance = ThreadLocalSingleton.getInstance();
    System.out.println(Thread.currentThread().getName() + " : " + instance);
    instance = ThreadLocalSingleton.getInstance();
    System.out.println(Thread.currentThread().getName() + " : " + instance);

    Thread t1 = new Thread(new ThreadExecutorTest());
    Thread t2 = new Thread(new ThreadExecutorTest());

    t1.start();
    t2.start();

    System.out.println("Program End");
}

1.3測試結果和分析

結果:

main : cn.net.health.tools.design.single.threadlocal.ThreadLocalSingleton@783e6358
main : cn.net.health.tools.design.single.threadlocal.ThreadLocalSingleton@783e6358
main : cn.net.health.tools.design.single.threadlocal.ThreadLocalSingleton@783e6358
main : cn.net.health.tools.design.single.threadlocal.ThreadLocalSingleton@783e6358
main : cn.net.health.tools.design.single.threadlocal.ThreadLocalSingleton@783e6358
Program End
Thread-0 : cn.net.health.tools.design.single.threadlocal.ThreadLocalSingleton@47f8df92
Thread-1 : cn.net.health.tools.design.single.threadlocal.ThreadLocalSingleton@7c180569
  • 不能保證整個程序唯一;

  • 可以保證線程唯一;

  • 每個線程中拿到的實例都是一個;

  • 不同的線程拿到的實例不是一個;

2. 主要應用場景

數據源動態路由

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