我试图通过线程执行在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
答案 0 :(得分:3)
您正在观察ThreadLocal
的整个点的行为:您在一个线程中设置的内容在另一个线程中是不可见的。您必须在的中设置ThreadLocal
值,并使用它们。