繁体   English   中英

为什么我的 ThreadLocal 的 initialValue() 不起作用?

[英]why doesn't my initialValue() of ThreadLocal work?

我想在 java 中测试ThreadLocal对象的使用,但似乎我的 initialValue() 不起作用。 我实际上在set() get()之前调用了get() ,它应该按预期返回 100 的变量ID 这是我的代码:

public class UsageThreadLocal implements Runnable {
    private AnotherThreadID<Long> var;

    public UsageThreadLocal(AnotherThreadID<Long> v) {
        this.var = v;
    }

    public void run() {
        try {
            print("var getThreadID =" + var.get());
            Thread.sleep(200);
            var.set(Thread.currentThread().getId());
            print("var getThreadID =" + var.get());
        } catch (InterruptedException x) {
        }
    }

    private static void print(String msg) {
        String name = Thread.currentThread().getName();
        System.out.println(name + ": " + msg);
    }

    public static void main(String[] args) {
        AnotherThreadID<Long> tid = new AnotherThreadID<Long>() {
            @Override
            public Long initialValue() {
                ID = new Long(100);
                System.out.println("I'm in initialValue()!");
                return ID;
            }
        };
        UsageThreadLocal shared = new UsageThreadLocal(tid);

        try {
            Thread threadA = new Thread(shared, "threadA");
            threadA.start();

            Thread.sleep(50);

            Thread threadB = new Thread(shared, "threadB");
            threadB.start();

            Thread.sleep(50);

            Thread threadC = new Thread(shared, "threadC");
            threadC.start();
        } catch (InterruptedException x) {
        }
    }
}

class AnotherThreadID<T> extends ThreadLocal<T> {
    public T ID;

    @Override
    public void set(T newID) {
        ID = newID;
    }

    @Override
    public T get() {
        return ID;
    }

}

并执行我的代码的结果:

threadA: var getThreadID =null
threadB: var getThreadID =null
threadC: var getThreadID =null
threadA: var getThreadID =9
threadB: var getThreadID =10
threadC: var getThreadID =11

我的代码有什么问题或者我误解了ThreadLocal的用法?

问题在于AnotherThreadID的实现。 ThreadLocal是为每个 Thread 保留一个值,你重写get()set()基本上使它不再是ThreadLocal

您可以删除AnotherThreadID类,并用ThreadLocal替换其他地方AnotherThreadID ,然后您的代码应该可以正常工作而无需进一步更改。

AnotherThreadID 应该由它的线程初始化,但你在主线程中初始化它。 而你只有一个AnotherThreadID实例。事实上,每个线程都应该有一个实例。

暂无
暂无

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

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