接受的答案回答了有关获取线程 ID 的问题,但它不允许您执行“线程 X 的 Y”消息。线程 ID 在线程之间是唯一的,但不一定从 0 或 1 开始。
下面是一个匹配问题的示例:
import java.util.concurrent.*;
class ThreadIdTest {
public static void main(String[] args) {
final int numThreads = 5;
ExecutorService exec = Executors.newFixedThreadPool(numThreads);
for (int i=0; i<10; i++) {
exec.execute(new Runnable() {
public void run() {
long threadId = Thread.currentThread().getId();
System.out.println("I am thread " + threadId + " of " + numThreads);
}
});
}
exec.shutdown();
}
}
和输出:
burhan@orion:/dev/shm$ javac ThreadIdTest.java && java ThreadIdTest
I am thread 8 of 5
I am thread 9 of 5
I am thread 10 of 5
I am thread 8 of 5
I am thread 9 of 5
I am thread 11 of 5
I am thread 8 of 5
I am thread 9 of 5
I am thread 10 of 5
I am thread 12 of 5
使用模算法进行轻微调整将允许您正确执行“线程 X of Y”:
// modulo gives zero-based results hence the +1
long threadId = Thread.currentThread().getId()%numThreads +1;
新结果:
burhan@orion:/dev/shm$ javac ThreadIdTest.java && java ThreadIdTest
I am thread 2 of 5
I am thread 3 of 5
I am thread 3 of 5
I am thread 3 of 5
I am thread 5 of 5
I am thread 1 of 5
I am thread 4 of 5
I am thread 1 of 5
I am thread 2 of 5
I am thread 3 of 5