gpt4 book ai didi

java - 为什么 ThreadLocal 变量需要静态化?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:01:17 30 4
gpt4 key购买 nike

我已经阅读了很多关于为什么 ThreadLocal 变量需要是静态的(虽然不是必需的)的文章,但我不明白为什么它应该是静态的。

我读过here和许多其他链接但没有明白这一点。

我做过这样的事

public class ThreadLocalDemo{

public static void main(String[]args)throws Exception{
SharedRersource r1= new SharedRersource();
Thread t1= new Thread(r1);
Thread t2= new Thread(r1);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Main thread Exiting...");
}

}

class SharedRersource implements Runnable{


private ThreadLocal<Integer> threadId = new ThreadLocal(){
protected Integer initialValue(){
return (int)(Math.random()*100);
}
};
public void run(){

try{
Thread.sleep(2000);
}
catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(threadId.get());

}
};

这里线程 t1 和 t2 拥有 threadId 的私有(private)副本而不是为什么它应该是静态的

请多多指教。谢谢

最佳答案

这个问题的答案在于 ThreadLocal 实现。

将 ThreadLocal 视为一个容器

ThreadLocal是一个容器,内部维护了一个ThreadLocalMap,这个ThreadLocalMap是threadlocal需要的关键是静态的(虽然不是必须的,但建议保持静态)。

因为我们想要每个类一个容器不是每个实例一个容器。如果我们每个实例都有一个容器,我们将拥有与实例一样多的容器,这将造成内存泄漏。

更多细节在这里

  1. http://www.0xcafefeed.com/2004/06/of-non-static-threadlocals-and-memory/
  2. https://www.appneta.com/blog/introduction-to-javas-threadlocal-storage/

关于java - 为什么 ThreadLocal 变量需要静态化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35764959/

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