我设置了所有线程共有的ThreadLocal初始值。调用构造函数时,我更改了值并正确打印。但是当启动线程时,它又重新变为初始值了吗?那是预期的吗?如果是,请解释什么?下面是我的两节课。提前致谢。


MyRunnableThreadLocal.java

public class MyRunnableThreadLocal implements Runnable {

private ThreadLocal<String> threadLocal = new ThreadLocal<String>(){
    @Override protected String initialValue() {
        return "Thread Name not set yet";
    }
};
public MyRunnableThreadLocal(String threadName) {
    System.out.println(threadLocal.get());
    threadLocal.set(threadName);
    System.out.println("Thread name: " + threadLocal.get());
}
@Override
public void run() {
    System.out.println(threadLocal.get());
    threadLocal.set(threadLocal.get() + " " + (Math.random() * 100D));
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
    }

    System.out.println(threadLocal.get());
}


}

ThreadLocalTest.java

public class ThreadLocalTest {

public static void main(String[] args) {
    Thread t1 = new Thread(new MyRunnableThreadLocal("Thread 1"));
    Thread t2 = new Thread(new MyRunnableThreadLocal("Thread 2"));

    t1.start();
    t2.start();
    try {
        t1.join();
        t2.join();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

}



输出:

Thread Name not set yet
Thread name: Thread 1
Thread Name not set yet
Thread name: Thread 2
Thread Name not set yet
Thread Name not set yet
Thread Name not set yet 20.24825634584746
Thread Name not set yet 59.67633602373702

最佳答案

ThreadLocal在运行代码的线程(及其关联的线程本地对象)中是本地的。

Thread Name not set yet <= runs in main
Thread name: Thread 1   <= runs in main for the first MyRunnableThreadLocal object
Thread Name not set yet <= runs in main for the 2nd MyRunnableThreadLocal object
Thread name: Thread 2   <= runs in main for the 2nd MyRunnableThreadLocal object
Thread Name not set yet <= runs in the first thread for the first MyRunnableThreadLocal
Thread Name not set yet <= runs in the 2nd thread for the 2nd MyRunnableThreadLocal
Thread Name not set yet 20.24825634584746  <= runs in the first thread for the first MyRunnableThreadLocal
Thread Name not set yet 59.67633602373702  <= runs in the 2nd thread for the 2nd MyRunnableThreadLocal


因此,您有三个线程和两个ThreadLocals。您的主线程同时使用本地线程和启动的两个线程,每个线程都有一个值。

每次您有一个新的ThreadLocal对象或新的Thread时,它都有一个新的初始值。


  设置线程本地值怎么办?


在创建另一个ThreadLocal或在另一个线程中使用它之前,您只能读取一次设置的值。


  如果前四行在主线程中运行,那么在第2行中设置的内容是否在第3行中没有反映?


第3行是另一个ThreadLocal中的另一个MyRunnableThreadLocal对象


  如果它在第一个MyRunnableThreadLocal对象上运行,那么为什么它不在第5或6行上反映呢?


第5和6行是第一次在这些线程中使用那些ThreadLocals,因此它们具有初始值。

注意:如果使用InheritableThreadLocal,它将按照您的期望进行操作。这是因为新线程“继承”了其父线程设置的值。

07-24 16:13