【问题标题】:How to get thread id from a thread pool?如何从线程池中获取线程 ID?
【发布时间】:2011-03-18 16:21:42
【问题描述】:

我有一个固定的线程池供我提交任务(仅限于 5 个线程)。我如何找出其中哪一个 5 线程执行我的任务(类似于“5 的线程 #3 正在执行此任务”)?

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?
    }
}

【问题讨论】:

    标签: java multithreading threadpool executorservice executors


    【解决方案1】:

    当前线程的获取方式有:

    Thread t = Thread.currentThread();
    

    获得 Thread 类对象 (t) 后,您可以使用 Thread 类方法获取所需的信息。

    线程 ID 获取:

    long tId = t.getId(); // e.g. 14291
    

    线程名称获取:

    String tName = t.getName(); // e.g. "pool-29-thread-7"
    

    【讨论】:

      【解决方案2】:

      如果您正在使用日志记录,那么线程名称将很有帮助。 线程工厂可以帮助解决这个问题:

      import org.slf4j.Logger;
      import org.slf4j.LoggerFactory;
      
      import java.util.concurrent.ExecutorService;
      import java.util.concurrent.Executors;
      import java.util.concurrent.ThreadFactory;
      
      public class Main {
      
          static Logger LOG = LoggerFactory.getLogger(Main.class);
      
          static class MyTask implements Runnable {
              public void run() {
                  LOG.info("A pool thread is doing this task");
              }
          }
      
          public static void main(String[] args) {
              ExecutorService taskExecutor = Executors.newFixedThreadPool(5, new MyThreadFactory());
              taskExecutor.execute(new MyTask());
              taskExecutor.shutdown();
          }
      }
      
      class MyThreadFactory implements ThreadFactory {
          private int counter;
          public Thread newThread(Runnable r) {
              return new Thread(r, "My thread # " + counter++);
          }
      }
      

      输出:

      [   My thread # 0] Main         INFO  A pool thread is doing this task
      

      【讨论】:

        【解决方案3】:

        已接受的答案回答了有关获取 a 线程 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 的 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 
        

        【讨论】:

        • Java 线程 ID 是否保证是连续的?否则,您的模数将无法正常工作。
        • @BrianGordon 不确定是否有保证,但代码似乎只不过是增加一个内部计数器:hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/…
        • 因此,如果同时初始化两个线程池,则其中一个线程池中的线程可能具有例如 1、4、5、6、7 的 ID,在这种情况下,您将有两个不同的线程具有相同的“我是线程 n 的 5”消息。
        • @BrianGordon Thread.nextThreadID() 是同步的,所以这不是问题,对吧?
        • @MatheusAzevedo 这与它无关。
        【解决方案4】:

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

        【讨论】:

          【解决方案5】:

          如果你的类继承自 Thread,你可以使用方法 getNamesetName 来命名每个线程。否则,您只需将name 字段添加到MyTask,并在构造函数中对其进行初始化。

          【讨论】:

            【解决方案6】:

            使用Thread.currentThread()

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

            【讨论】:

            • 这实际上不是我们想要的答案;应该改用% numThreads
            • @petrbel 他完美地回答了问题标题,并且在我看来,当 OP 请求“类似于 'thread #3 of 5”时,线程 ID 已经足够接近了。
            • 请注意,getId() 的示例输出是 14291,而 getName() 为您提供 pool-29-thread-7,我认为它更有用。
            猜你喜欢
            • 2010-12-13
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-11-24
            • 2012-01-28
            • 1970-01-01
            • 1970-01-01
            • 2016-09-29
            相关资源
            最近更新 更多