Threadlocal变量出现为null

时间:2015-02-05 12:26:29

标签: java multithreading thread-local

我试图通过线程执行在run方法中打印threadlocal变量,但它显然是null。请找到信息代码---

public class EvenAndOdd implements Runnable{

public EvenAndOdd() {

}

public  static void setThreadContext(){
 threadLocal.set(3);
 eventhreadLocal.set(2);
}
 private static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();
 private static ThreadLocal<Integer> eventhreadLocal = new ThreadLocal<Integer>(); 

@Override
public void run() {
    System.out.println(threadLocal.get());
    System.out.println(eventhreadLocal.get());
}

}

//现在用于创建线程并调用run方法的类

public class PrintNumber {
public static void main(String[] args) {

    EvenAndOdd evenAndOdd =new EvenAndOdd();
    EvenAndOdd.setThreadContext();
    Thread printThread = new Thread(evenAndOdd);
    printThread.start();

}
}

问题陈述---线程的执行给我null而不是2&amp; 3

1 个答案:

答案 0 :(得分:3)

您正在观察ThreadLocal的整个的行为:您在一个线程中设置的内容在另一个线程中是不可见的。您必须在中设置ThreadLocal值,并使用它们。