threadLocal 中的“withInitial”与“InitialValue”

Pra*_*wal 2 java multithreading thread-local java-8 inheritable-thread-local

我对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
Child Thread Value : parent data
Run Code Online (Sandbox Code Playgroud)

我在父线程中创建线程,并调用子线程。子线程从父线程继承数据。

现在,如果我data像这样初始化变量(在第 2 行):

public static ThreadLocal<String> data =InheritableThreadLocal.withInitial(() -> "temp");
Run Code Online (Sandbox Code Playgroud)

我得到以下输出:

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

我不确定为什么会发生。我阅读了 oracle 的文档,但没有得到有用的信息。 https://docs.oracle.com/javase/8/docs/api/java/lang/ThreadLocal.html#withInitial-java.util.function.Supplier- https://docs.oracle.com/javase/8/ docs/api/java/lang/ThreadLocal.html#initialValue--

我想知道如何使用withInitial而不是使用来实现相同的输出initialValue

Swe*_*per 5

withInitial不会创建InheritableThreadLocal. 它只创建一个常规ThreadLocal,这就是您temp在输出中看到的原因。

withInitial是一个静态方法,所以它不能被覆盖InheritableThreadLocal来做一些不同的事情,比如返回一个InheritableThreadLocal.

所以你不能做同样的事情,但是使用withInitial, 因为它不返回你需要的对象类型。