【发布时间】:2019-05-05 03:46:13
【问题描述】:
主线程如何访问另一个线程的threadlocal?尽管另一个线程的 threadlocal 在主线程中给出的值与它在自己的 run 方法中给出的值不同。
class MyThread13 extends Thread{
static int id =0;
ThreadLocal threadLocal = new ThreadLocal(){
public Integer initialValue(){
return ++id;
}
};
public MyThread13(String name){
super(name);
}
public void run(){
System.out.println(Thread.currentThread().getName()+" is executing with id :"+threadLocal.get());
}
}
public class MultiThreading13ThreadLocalB {
public static void main(String[] args) {
MyThread13 myThread13a = new MyThread13("Thread:1");
MyThread13 myThread13b = new MyThread13("Thread:2");
myThread13a.start();
myThread13b.start();
myThread13c.start();
// myThread13d.start();
System.out.println("Accessing threadlocal from main :"+myThread13a.threadLocal.get());
}
}
当从主线程访问另一个线程的threadlocal时,它应该给null。但在这里它给出了一些其他的价值
【问题讨论】:
标签: java multithreading thread-local