gpt4 book ai didi

Java ThreadLocal 静态?

转载 作者:太空狗 更新时间:2023-10-29 22:42:00 24 4
gpt4 key购买 nike

在线程本地设置一个值:

//Class A holds the static ThreadLocal variable.

Class A{

public static ThreadLocal<X> myThreadLocal = new ThreadLocal<X>();
....
}


//A Class B method sets value in A's static ThreadLocal variable
class B{
{
public void someBmethod(){
X x = new X();
A.myThreadLocal.set(x);
}
}


//Class C retrieves the value set in A's Thread Local variable.

Class C {

public void someCMethod(){
X x = A.myThreadLocal.get();
}
...
}

问题:
现在假设这是一个网络应用程序,并且线程按顺序执行:B.someBMethod、C.someCMethod。

多个线程执行 B 的 someBMethod,最终将更新 SAME A 的静态 ThreadLocal 变量 myThreadLocal,从而违背了 ThreadLocal 变量的目的。 (根据文档建议对 ThreadLocal 使用静态。)

C 的 someCMethod,从 ThreadLocal 获取值时可能无法获取“当前”线程设置的值。

我在这里错过了什么?

最佳答案

根据 ThreadLocal 的定义类

This class provides thread-local variables. These variables differfrom their normal counterparts in that each thread that accesses one(via its get or set method) has its own, independently initializedcopy of the variable. ThreadLocal instances are typically privatestatic fields in classes that wish to associate state with a thread(e.g., a user ID or Transaction ID).

这意味着 2 个线程 t1t2 执行 someBMethod() 并且他们最终设置 x1 & x2(X 的实例)分别。现在,当 t1 出现并执行 someCMethod() 时,它会得到 x1(由 自身设置/strong> 更早)并且 t2 得到 x2

换句话说,拥有 ThreadLocal 的单个静态实例是安全的,因为当您调用 set

时,它在内部会执行类似这样的操作
set(currentThread, value) //setting value against that particular thread

当你调用 get 时

get(currentThread) //getting value for the thread

关于Java ThreadLocal 静态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16249687/

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