定义
为共享变量在每个线程中创建一个副本,每个线程可以访问自己内部的副本变量。
使用
public class ThreadLocalTest {
private static Integer num = 0;
private static ThreadLocal<Integer> numberLocal = new ThreadLocal<Integer>(){
protected Integer initialValue(){
return 0;
}
};
public static void main(String[] args) {
Thread[] thread = new Thread[5];
for (int i=0;i<thread.length;i++){
thread[i]=new Thread(()->{
// num+=5;
int x = numberLocal.get().intValue();
x+=5;
numberLocal.set(x);
System.out.println(Thread.currentThread().getName()+":"+x);
},"Thread-"+i);
}
for (int i=0;i<thread.length;i++){
thread[i].start();
}
}
}