如何从线程池中获取线程ID?

ser*_*erg 127 java multithreading executorservice threadpool executors

我有一个固定的线程池,我提交任务(限于5个线程).如何找出这5个线程中的哪一个执行我的任务(类似"线程#3 of 5正在执行此任务")?

ExecutorService taskExecutor = Executors.newFixedThreadPool(5);

//in infinite loop:
taskExecutor.execute(new MyTask());
....

private class MyTask implements Runnable {
    public void run() {
        logger.debug("Thread # XXX is doing this task");//how to get thread id?
    }
}
Run Code Online (Sandbox Code Playgroud)

ska*_*man 219

使用Thread.currentThread():

private class MyTask implements Runnable {
    public void run() {
        long threadId = Thread.currentThread().getId();
        logger.debug("Thread # " + threadId + " is doing this task");
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这实际上不是理想的答案; 一个人应该使用`%numThreads`代替 (3认同)
  • 请注意,“getId()”的示例输出是“14291”,其中“getName()”为您提供“pool-29-thread-7”,我认为它更有用。 (3认同)
  • @petrbel他正在完美地回答问题标题,并且当OP请求"类似'第3个主题的第5个"之类的东西时,我认为线程ID足够接近. (2认同)

Bur*_*Ali 26

接受的答案回答了关于获取问题一个线程ID,但它不会让你的邮件"Y的主题X".线程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();
  }
}
Run Code Online (Sandbox Code Playgroud)

和输出:

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
Run Code Online (Sandbox Code Playgroud)

使用模运算的轻微调整将允许您正确执行"Y的线程X":

// modulo gives zero-based results hence the +1
long threadId = Thread.currentThread().getId()%numThreads +1;
Run Code Online (Sandbox Code Playgroud)

新结果:

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 
Run Code Online (Sandbox Code Playgroud)

  • 因此,如果同时初始化两个线程池,其中一个线程池中的线程可能具有ID,例如,1,4,5,6,7,在这种情况下,您将拥有两个不同的线程,具有相同的"我是线程n的5"消息. (6认同)
  • Java线程ID是否保证是连续的?如果没有,您的模数将无法正常工作. (5认同)

Vin*_*lds 6

您可以使用Thread.getCurrentThread.getId(),但是当记录器管理的LogRecord对象已经具有线程Id 时,您为什么要这样做?我认为你缺少一个记录日志消息的线程ID的配置.