![](/img/trans.png)
[英]Why initialValue of ThreadLocal doesn't increment my variables?
[英]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.