简体   繁体   English

主线程可以访问线程的Threadlocal

[英]Threadlocal of a thread is accessible to main thread

How main thread is able to access threadlocal of another thread? 主线程如何能够访问另一个线程的threadlocal? Although threadlocal of another thread gives another value in main thread than what it gives inside its own run method. 虽然另一个线程的threadlocal在主线程中给出了另一个值,而不是它在自己的run方法中给出的值。

class MyThread13 extends Thread{
    static int id =0;
     ThreadLocal threadLocal = new ThreadLocal(){
       public Integer initialValue(){
            return ++id;
        }
    };
    public MyThread13(String name){
        super(name);
    }
    public void run(){
        System.out.println(Thread.currentThread().getName()+" is executing with id :"+threadLocal.get());

    }

}

public class MultiThreading13ThreadLocalB {
    public static void main(String[] args) {
        MyThread13 myThread13a = new MyThread13("Thread:1");
        MyThread13 myThread13b = new MyThread13("Thread:2");
        myThread13a.start();
        myThread13b.start();
        myThread13c.start();
       // myThread13d.start();
        System.out.println("Accessing threadlocal from main :"+myThread13a.threadLocal.get());

    }
}

when threadlocal of another thread is being accessed from main thread , it should give null. 当从主线程访问另一个线程的threadlocal时,它应该为null。 But here it is giving some other value 但这里给出了一些其他价值

Your example shows a confusion of ThreadLocal with what are simply member variables of Thread instances. 您的示例显示了ThreadLocalThread实例的简单成员变量的混淆。 The concepts are similar; 概念类似; both allow you to associate state with a Thread instance, but a ThreadLocal allows you to do it outside of the thread instance itself. 两者都允许您将状态与Thread实例相关联,但ThreadLocal允许您在线程实例本身之外执行它。 As you've noted, a ThreadLocal lives up to its name -- when you call get and set on it, those values are specific to that thread, which is why trying to access another thread's state (as the main thread tries to do in your example) is not going to work. 正如您所指出的, ThreadLocal的名称ThreadLocal - 当您调用getset它时,这些值是特定于该线程的,这就是为什么尝试访问另一个线程的状态(正如主线程尝试进行的那样)你的例子)不会起作用。

ThreadLocal s are sometimes helpful, but in day to day programming there is rarely a need for them. ThreadLocal有时很有用,但在日常编程中很少需要它们。 One kind of use case would be something like a server process that accepts an incoming request and associates some state with that request; 一种用例类似于服务器进程,它接受传入的请求并将某个状态与该请求相关联; if you don't want to change all of your method signatures to pass that state through, you could put it in a ThreadLocal . 如果您不想更改所有方法签名以通过该状态,则可以将其放在ThreadLocal Usually there is a single ThreadLocal instance per JVM. 通常每个JVM都有一个ThreadLocal实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM