分析:
- ThreadLocal :提供线程内的局部变量,这种变量在线程的生命周期内起作用
- Thread 局部变量:线程内部的变量
二者有啥区别,怎么看 都觉得 二者一摸一样,请大家分析分析 ThreadLocal 在什么场景下,用它比用 Thread 的局部变量好。
自写的测试代码:
public class ThreadLocalTest {
private static final ThreadLocal<Integer> value = new ThreadLocal<Integer>() {
@Override
protected Integer initialValue() {
return 0;
}
};
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
new Thread(new MyThread(i + "")).start();
}
}
static class MyThread implements Runnable {
private String index;
public MyThread(String index) {
this.index = index;
}
//局部变量
private Integer num = 0;
public void run() {
System.out.println("线程" + index + "的初始 num:" + num);
System.out.println("线程" + index + "的初始 value:" + value.get());
for (int i = 0; i < 10; i++) {
num += i;
value.set(value.get() + i);
}
System.out.println("线程" + index + "的累加 num:" + num);
System.out.println("线程" + index + "的累加 value:" + value.get());
}
}
}