ThreadLocal实现线程单例

提示:其实是伪线程安全的。
使用场景:ORM框架中实现多数据源动态切换。

public class ThreadLocalSingleton {
    private static final ThreadLocal<ThreadLocalSingleton> threadLocalInstance =
            new ThreadLocal<ThreadLocalSingleton>(){
                @Override
                protected ThreadLocalSingleton initialValue() {
                    return new ThreadLocalSingleton();
                }
            };

    private ThreadLocalSingleton(){}

    public static ThreadLocalSingleton getInstance(){
        return threadLocalInstance.get();
    }
}
public static void main(String[] args) { 
	System.out.println(ThreadLocalSingleton.getInstance()); 
	System.out.println(ThreadLocalSingleton.getInstance()); 
	System.out.println(ThreadLocalSingleton.getInstance()); 
	System.out.println(ThreadLocalSingleton.getInstance()); 
	System.out.println(ThreadLocalSingleton.getInstance());
	Thread t1 = new Thread(new ExectorThread()); 
	Thread t2 = new Thread(new ExectorThread()); 
	t1.start(); 
	t2.start();
	System.out.println("End"); 
}

结果:
在这里插入图片描述
mian线程,Thread-1线程,Thread-0线程,各自线程中是唯一的,但是各个线程之间是互不一样的。
通过查看ThreadLocal的源码
在这里插入图片描述
ThreadLocalMap的set方法key其实就是当前的线程本身,value就是我们放到map中的value的值,所以就保证了上面出现的结果。即线程内是安全的。

这里其实是注册式单利中的容器类

Java糖果罐
扫码关注
原文地址:https://www.cnblogs.com/LeesinDong/p/12246633.html