标签: inheritable-thread-local

threadLocal 中的“withInitial”与“InitialValue”

我对threadLocal的initialValuewithInital方法有点困惑。

考虑一种情况,我在父线程中有数据,并且我正在使用InheritableThreadLocal.

public class Parent extends Thread {
public static ThreadLocal<String> data = new InheritableThreadLocal<String>() {
    @Override
    protected String initialValue() {
        return "temp";
    }
};

public static void main(String[] args) {
    new Parent().start();
}

public void run() {
    data.set("parent data");
    System.out.println("Parent Thread Value :" + data.get());
    new ChildThread().start();
}

class ChildThread extends Thread {
    public void run() {
        System.out.println("Child Thread Value :" + Parent.data.get());
    }
}
}
Run Code Online (Sandbox Code Playgroud)

输出:

Parent Thread Value : parent data …
Run Code Online (Sandbox Code Playgroud)

java multithreading thread-local java-8 inheritable-thread-local

2
推荐指数
1
解决办法
72
查看次数