我正在处理互斥分配,但是当我开始时我注意到我的应用程序的线程 ID 从 9 开始。当我再次编译和执行它时它没有改变。有没有我遗漏的问题,或者 Java 线程 ID 可以从任意数字开始? This question相关的。
对于那些感兴趣的人,这里有一个来自 Herlihy 和 Shavit 的“多处理器编程艺术”的类(class),用于对线程进行编号:
public class ThreadID {
private static volatile int nextID = 0;
private static class ThreadLocalID extends ThreadLocal<Integer> {
protected synchronized Integer initialValue() {
return nextID++;
}
}
private static ThreadLocalID threadID = new ThreadLocalID();
public static int get() {
return threadID.get();
}
public static void set(int index) {
threadID.set(index);
}
}
然后你可以调用
ThreadID.get();
它将自动递增数字并始终从 1 开始。
最佳答案
来自Thread#getId()
文档:
Returns the identifier of this Thread. The thread ID is a positive long number generated when this thread was created. The thread ID is unique and remains unchanged during its lifetime. When a thread is terminated, this thread ID may be reused.
没有任何迹象表明它保证会从 0 开始。我猜想,在内部,Java 在您创建第一个 Thread 对象之前创建了几个 Thread 对象,因此线程 ID 0-8 已经被占用。但是,文档中的任何内容都不能保证此数字将以任何方式顺序排列(尽管当前是这样实现的),因此您不应依赖于此。
关于java - Java 线程 ID 应该总是从 0 开始吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1262051/