Answers
class ThreadLocalSingleton {
private ThreadLocalSingleton(){}
public final static ThreadLocal<ThreadLocalSingleton> INSTANCE =
new ThreadLocal<ThreadLocalSingleton>(){
@Override
protected ThreadLocalSingleton initialValue(){
return new ThreadLocalSingleton();
}
};
}
public class ThreadLocalSingletonTest{
@Test
public void testThreadLocalSingleton() throws InterruptedException{
for(int i=0; i<5; i++){
new Thread(new Runnable(){
@Override
public void run() {
System.out.println(ThreadLocalSingleton.INSTANCE.get());
}
}).start();
}
Thread.sleep(3000);
}
}
结果, 每个thread都对应唯一的不可变的 ThreadLocalSingleton实例:
com.test.loader.ThreadLocalSingleton@7d7c214d
com.test.loader.ThreadLocalSingleton@606e8697
com.test.loader.ThreadLocalSingleton@784654f6
com.test.loader.ThreadLocalSingleton@5174202a
com.test.loader.ThreadLocalSingleton@1eebcf2d
悲剧D团子
answered 11 years, 7 months ago