【发布时间】:2014-05-12 01:12:36
【问题描述】:
这是 ThreadLocal 使用的 java doc 中的示例。
public class ThreadId {
// Atomic integer containing the next thread ID to be assigned
private static final AtomicInteger nextId = new AtomicInteger(0);
// Thread local variable containing each thread's ID
private static final ThreadLocal<Integer> threadId =
new ThreadLocal<Integer>() {
@Override protected Integer initialValue() {
return nextId.getAndIncrement();
}
};
// Returns the current thread's unique ID, assigning it if necessary
public static int get() {
return threadId.get();
}
}
我不明白为什么我们在这里使用 threadlocal。 AtomicInteger 不是已经线程安全了吗?
把代码改成这个怎么样?
public class ThreadId {
// Atomic integer containing the next thread ID to be assigned
private static final AtomicInteger nextId = new AtomicInteger(0);
// Returns the current thread's unique ID, assigning it if necessary
public static int get() {
return nextId.getAndIncrement();
}
}
我也不明白这是什么意思:
这些变量与普通变量的不同之处在于,每个访问一个(通过其 get 或 set 方法)的线程都有自己的、独立初始化的变量副本。
那么,ThreadLocal(内部)是否为每个线程保存一个整数数组? Java_concurrency 在实践中提到我们可以将 threadLocal 视为 Map。
提前致谢。
【问题讨论】:
标签: java multithreading concurrency