package t1;
public class TestThread7 {
private static volatile ThreadLocal<String> userId = new ThreadLocal<String>();
public static void main(String[] args) {
Runnable r = () -> {
String name = Thread.currentThread().getName();
if ("A".equals(name)) {
userId.set("fortrot");// 当不设置此值时,会调用initialValue()方法设置为初始值null
} else {
userId.set("charlie");
}
System.out.println(name + " " + userId.get());
new A().get();
new B().get();
};
new Thread(r, "A").start();
new Thread(r, "B").start();
}
static class A {
public void get() {
System.out.println(Thread.currentThread().getName() + ":" + userId.get());
}
}
static class B {
public void get() {
System.out.println(Thread.currentThread().getName() + ":" + userId.get());
}
}
}
输出结果:
原文:https://www.cnblogs.com/dengw125792/p/12602971.html