为什么ThreadLocal变量需要静态? [英] Why ThreadLocal variable need to static?

查看:1380
本文介绍了为什么ThreadLocal变量需要静态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经读过很多文章,说明为什么ThreadLocal变量需要是静态的(尽管不是必需的),但是我不知道为什么它应该是静态的.

I have read many articles on why ThreadLocal variable need to be static(although not necessary), but I didn't get the idea why it should be static.

我已经在此处阅读过链接,但不知道.

我已经做了类似的事情

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的私有副本,而不是为什么它应该是静态的

请给我更好的理解. 谢谢

Please give a better understanding to me. Thanks

推荐答案

此问题的答案在于ThreadLocal实现.

Answer to this question lies into ThreadLocal implementation .

将ThreadLocal视为容器

ThreadLocal是在内部维护ThreadLocalMap的容器,此ThreadLocalMap是为什么threadlocal需要为静态的关键(虽然不是必需的,但建议保持其静态).

ThreadLocal is a container that maintain a ThreadLocalMap internally , This ThreadLocalMap is the key why threadlocal need to be static(although not necessary ,but suggestion is keep it static).

因为我们想要 single container per class not container per instance.如果每个实例都有容器,那么我们将拥有与实例一样多的容器,这将导致内存泄漏.

Because we want single container per class , not container per instance .If we have container per instance we will be having as many container as instance and that will created memory leak .

更多详细信息

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

这篇关于为什么ThreadLocal变量需要静态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆