Preface
![Insert picture description here](https://img-blog.csdnimg.cn/20210209131320579.png)
ThreadLocal has isolation
public class Demo17 {
public static void main(String[] args) {
ThreadLocal<String> threadLocal = new ThreadLocal<>();
Demo17ThreadA threadA = new Demo17ThreadA(threadLocal);
threadA.setName("线程A");
threadA.start();
Demo17ThreadA threadB = new Demo17ThreadA(threadLocal);
threadB.setName("线程B");
threadB.start();
}
}
class Demo17ThreadA extends Thread{
private ThreadLocal<String> threadLocal;
public Demo17ThreadA(ThreadLocal<String> threadLocal){
this.threadLocal = threadLocal;
}
@SneakyThrows
@Override
public void run() {
for (int i = 0; i < 10; i++) {
threadLocal.set(Thread.currentThread().getName() + "第"+(i+1)+"个值");
System.out.println(threadLocal.get());
Thread.sleep(500);
}
}
}
operation result
![Insert picture description here](https://img-blog.csdnimg.cn/20210209133525426.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmdsZV8wOTEw,size_16,color_FFFFFF,t_70)