ThreadLocalJDK 中的文档
JDK 1.6 文档显示了有关如何使用 LocalThread
的示例。我将其复制并粘贴到此处:
例如,下面的类生成每个线程本地的唯一标识符。线程的 id 在第一次调用 UniqueThreadIdGenerator.getCurrentThreadId()
时分配,并在后续调用中保持不变。
import java.util.concurrent.atomic.AtomicInteger;
public class UniqueThreadIdGenerator {
private static final AtomicInteger uniqueId = new AtomicInteger(0);
private static final ThreadLocal <Integer> uniqueNum =
new ThreadLocal <Integer> () {
@Override
protected Integer initialValue() {
return uniqueId.getAndIncrement();
}
};
public static int getCurrentThreadId() {
return uniqueId.get();
}
} // UniqueThreadIdGenerator
我的问题是:
当多个线程调用 UniqueThreadIdGenerator.getCurrentThreadId()
时,它只返回 0,因为没有初始化。难道不应该是这样的:
public static int getCurrentThreadId() {
return uniqueNum.get();
}
现在在第一次调用之后,它会初始化变量。
JDK 1.6 documentation shows an example about how to use LocalThread<T>
. I copy and paste it here:
For example, the class below generates unique identifiers local to each thread. A thread's id is assigned the first time it invokes UniqueThreadIdGenerator.getCurrentThreadId()
and remains unchanged on subsequent calls.
import java.util.concurrent.atomic.AtomicInteger;
public class UniqueThreadIdGenerator {
private static final AtomicInteger uniqueId = new AtomicInteger(0);
private static final ThreadLocal <Integer> uniqueNum =
new ThreadLocal <Integer> () {
@Override
protected Integer initialValue() {
return uniqueId.getAndIncrement();
}
};
public static int getCurrentThreadId() {
return uniqueId.get();
}
} // UniqueThreadIdGenerator
My problem is:
when multiple threads call UniqueThreadIdGenerator.getCurrentThreadId()
it only returns 0 because there is no initialization. Shouldn't it be like this:
public static int getCurrentThreadId() {
return uniqueNum.get();
}
Now after the first call, it goes and initialize the variable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,它应该是
uniqueNum.get()
。 JDK 7 文档 说得对,并且使用更好的名称:这实际上并不是初始化的问题 - 这只是完全使用错误的成员的问题。即使许多代码在原始代码中使用了
uniqueNum
,getCurrentThreadId()
也始终会返回“要分配的下一个 ID” “为当前线程分配的ID”。Yes, it should be
uniqueNum.get()
. The JDK 7 docs get it right, and use better names:It's not really a matter of initialization though - it's simply a matter of using the wrong member entirely. Even if lots of code had used
uniqueNum
in the original code,getCurrentThreadId()
would always have returned "the next ID to be assigned" instead of "the ID assigned for the current thread".