ThreadLocal不能保证对象全局唯一,但是能保证在单个线程中是唯一的,天生线程安全;
public class ThreadLocalSingleton {
private static final ThreadLocal<ThreadLocalSingleton> THREAD_LOCAL_SINGLETON_THREAD_LOCAL = new ThreadLocal<ThreadLocalSingleton>(){
@Override
protected ThreadLocalSingleton initialValue() {
return new ThreadLocalSingleton();
}
};
/**
* 构造器私有
*/
private ThreadLocalSingleton(){
}
public static ThreadLocalSingleton getInstance(){
return THREAD_LOCAL_SINGLETON_THREAD_LOCAL.get();
}
}
测试代码:
public static void main(String[] args) throws Exception {
ThreadLocalSingleton.getInstance();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+" "+ThreadLocalSingleton.getInstance());
}
},"线程1").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+" "+ThreadLocalSingleton.getInstance());
}
},"线程2").start();
TimeUnit.SECONDS.sleep(5);
}
结论:
在同一个线程里,对象是单例的。
原因:
单例一般为了线程安全要给方法上锁,用时间换空间,而ThreadLocal会把所有的对象放到ThreadLocalMap中,每个线程都提供一个对象,实际上是空间换时间实现线程隔离的。