/**
* @Author: ZhangHao
* @Description: ThreadLocal测试
* @Date: 2020/10/15 20:42
* @Version: 1.0
*/
public class ThreadLocalTest {
/**
* 非线程隔离式数据
*/
int i = 0;
@Test
void test1(){
Thread[] threads = new Thread[5];
for(int j = 0;j < threads.length;j++){
threads[j] = new Thread(() -> {
System.out.println(++i);
});
}
for(int j = 0;j < threads.length;j++){
threads[j].start();
}
}
/**
* 线程隔离式数据
*/
/*ThreadLocal<Integer> threadLocal = new ThreadLocal<>(){
@Override
protected Integer initialValue() {
return 0;
}
};*/
ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);
@Test
void test2(){
Thread[] threads = new Thread[5];
for(int j = 0;j < threads.length;j++){
threads[j] = new Thread(() -> {
int i1 = threadLocal.get();
System.out.println(++i1);
});
}
for(int j = 0;j < threads.length;j++){
threads[j].start();
}
}
/**
* 线程隔离式单例
*/
private static final ThreadLocal<SingleTon> threadLocal1 = ThreadLocal.withInitial(() -> new SingleTon());
public static SingleTon getInstance(){
return threadLocal1.get();
}
static class SingleTon{
private SingleTon(){
}
}
}
Thread中有:
ThreadLocal.ThreadLocalMap threadLocals = null;
ThreadLocalMap中有:
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}