ThreatLocal的测试

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());
}
}

}

 

输出结果:

 

posted @ 2020-03-31 09:07  工设091  阅读(93)  评论(0)    收藏  举报