建设者
ThreadOne
由主线程执行,因此,语句
USERNAME.set(username);
在这个构造函数中设置主线程的值。但是主线程的可继承线程局部变量的实际值被复制到构造函数中
Thread
,即前面的
super(threadName);
,已经。
因此,第一个线程继承了第一个线程之前的状态
USERNAME.set(用户名);
调用,而第二个线程继承调用后的状态;继承关系无关紧要,正如我们可以证明的那样:
public class InheritableThreadLocalExample {
public static void main(String[] args) {
ThreadOne threadOne = new ThreadOne("user-one", "thread-one");
printValue();
threadOne.start();
Thread threadTwo = new Thread(
InheritableThreadLocalExample::printValue, "thread-two");
ThreadOne.USERNAME.set("user-two");
threadTwo.start();
}
static void printValue() {
System.out.println(Thread.currentThread().getName()
+ ". Username: " + ThreadOne.USERNAME.get());
}
public static class ThreadOne extends Thread {
protected static final InheritableThreadLocal<String> USERNAME
= new InheritableThreadLocal<>();
public ThreadOne(String username, String threadName) {
super(threadName);
USERNAME.set(username);
}
@Override
public void run() {
printValue();
}
}
}
main. Username: user-one
thread-one. Username: null
thread-two. Username: user-one
我们可以很容易地在主线程中设置预期的值,而不需要子类:
public class InheritableThreadLocalExample {
static final InheritableThreadLocal<String> USERNAME
= new InheritableThreadLocal<>();
public static void main(String[] args) {
USERNAME.set("user-one");
Thread threadOne = new Thread(
InheritableThreadLocalExample::printValue, "thread-one");
USERNAME.set("user-two");
Thread threadTwo = new Thread(
InheritableThreadLocalExample::printValue, "thread-two");
USERNAME.remove();
threadOne.start();
threadTwo.start();
}
static void printValue() {
System.out.println(Thread.currentThread().getName()
+ ". Username: " + USERNAME.get());
}
}
thread-one. Username: user-one
thread-two. Username: user-two