简体   繁体   English

ThreadLocal与线程局部变量

[英]ThreadLocal vs thread local variable

What is difference in ThreadLocal.get/put and ThreadLocal.get/put和有什么区别

class ThreadT extends Thread {
private SomeObj obj;
.....
}

I believe, please correct me if I am wrong, this obj will also be different for each thread. 我相信,如果我错了,请纠正我,这个obj对于每个帖子也会有所不同。 ie, if we are having 5 objects of the ThreadT, we will be having each five of them having different objects of obj. 也就是说,如果我们有3个ThreadT对象,我们将使每个对象具有不同的obj对象。

So if this is the case, then why do we need to have the need to use ThreadLocal ? 那么如果是这种情况,那么为什么我们需要使用ThreadLocal呢?

Please correct me if I my understanding about either of the two is incorrect. 如果我对两者中的任何一个的理解不正确,请纠正我。

From the documentation 从文档中

This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable.

Your approach will work if you are writing classes that are directly going to extend thread. 如果您正在编写直接扩展线程的类,那么您的方法将起作用。 But what about classes that need a ThreadLocal variable but doesn't have direct access to it's Thread instance? 但是那些需要ThreadLocal变量但是没有直接访问它的Thread实例的类呢?

In such cases ThreadLocal is useful. 在这种情况下,ThreadLocal很有用。 Specially in server environments where you don't directly use the threads most of the time. 特别是在大多数情况下不直接使用线程的服务器环境中。

The fact that your class extends Thread does not make its fields special. 您的类扩展Thread的事实并不会使其字段特殊。 Assuming your class has get / set methods 假设你的类有get / set方法

    final ThreadT tt = new ThreadT();

    new Thread() {
        public void run() {
            tt.set(new Object());
        };
    }.start();

    new Thread() {
        public void run() {
            Object obj = tt.get();
        };
    }.start();

the second thread will get the object which first thread put. 第二个线程将获取第一个线程放置的对象。 It wouldnt happen with ThreadLocal 它不会发生在ThreadLocal上

I have written program 我写了程序

class ThreadRun implements Runnable {

    NumberValue number;
    int value;

    ThreadRun(NumberValue number,int value) {


        this.number=number;
        this.value = value;
        Thread t = new Thread(this);
        t.start();
    }

    @Override
    public void run() {

        number = number.getThreadLocal();


        number.setId(number.getId()+value);

        System.out.println(number.getId());

    }

}

public class ThreadTest {
    public static void main(String[] args) {
        NumberValue number = new NumberValue(1);


        new ThreadRun(number, 1);
        new ThreadRun(number, 2);
    }
}

class NumberValue {

    int id;



    ThreadLocal<NumberValue> threadLocal = new ThreadLocal<NumberValue>() {

    @Override
    protected NumberValue initialValue() {

        return new NumberValue(id);
    }
    };



    NumberValue(int id) {
        this.id = id;

    }



    /**
     * @return the id
     */
    public int getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(int id) {
        this.id = id;
    }
    public NumberValue getThreadLocal() {
        return threadLocal.get();
    }






}

output: 2 3 this output is our expected output 输出:2 3此输出是我们的预期输出

But when you comment 但是当你发表评论时

// number = number.getThreadLocal(); // number = number.getThreadLocal(); and run program output will be output: 3 4 So the data is corrupted when // number = number.getThreadLocal(); 并输出运行程序输出:3 4因此// number = number.getThreadLocal()时数据被破坏; is commented.So threadlocal make a local copy of NumberValue .But when threadlocal is not used same object instance is shared between threads ,so data result is corrupted than actaul result 注释。所以threadlocal生成NumberValue的本地副本。但是当没有使用threadlocal时,线程之间共享相同的对象实例,因此数据结果被破坏而不是actaul结果

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

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