gpt4 book ai didi

java - "withInitial"与 "InitialValue"在 threadLocal 中

转载 作者:行者123 更新时间:2023-12-05 09:32:01 24 4
gpt4 key购买 nike

我对 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());
}
}
}

输出:

Parent Thread Value : parent data
Child Thread Value : parent data

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

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

public static ThreadLocal<String> data =InheritableThreadLocal.withInitial(() -> "temp");

我得到以下输出:

Parent Thread Value :parent data
Child Thread Value :temp

我不确定为什么会这样。我阅读了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 获得相同的输出?

最佳答案

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

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

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

关于java - "withInitial"与 "InitialValue"在 threadLocal 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68441986/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com