新闻资讯
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();
}
}
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();
}
}
mian线程,Thread-1线程,Thread-0线程,各自线程中是唯一的,但是各个线程之间是互不一样的。
通过查看ThreadLocal的源码
ThreadLocalMap的set方法key其实就是当前的线程本身,
value就是我们放到map中的value的值,所以就保证了上面出现的结果。即线程内是安全的。
回复列表