提示:其实是伪线程安全的。
使用场景: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的值,所以就保证了上面出现的结果。即线程内是安全的。
这里其实是注册式单利中的容器类