代码之家  ›  专栏  ›  技术社区  ›  serg

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

  •  122
  • serg  · 技术社区  · 16 年前

    我有一个固定的线程池,可以将任务提交给它(仅限于 5 5 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?
        }
    }
    
    6 回复  |  直到 10 年前
        1
  •  245
  •   skaffman    16 年前

    使用 Thread.currentThread() :

    private class MyTask implements Runnable {
        public void run() {
            long threadId = Thread.currentThread().getId();
            logger.debug("Thread # " + threadId + " is doing this task");
        }
    }
    
        2
  •  24
  •   Burhan Ali    12 年前

    公认的答案回答了关于获得 线程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 
    
        3
  •  6
  •   Vineet Reynolds    16 年前

    您可以使用Thread.getCurrentThread.getId(),但为什么要在 LogRecord 由记录器管理的对象已经具有线程Id。我认为您在某个地方缺少一个用于记录日志消息的线程Id的配置。

        4
  •  2
  •   Vitaliy Polchuk    9 年前

    线程工厂有助于:

    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
    
        5
  •  1
  •   Justin Ethier    16 年前

    如果您的类继承自 Thread ,可以使用方法 getName setName name 字段到 MyTask ,并在构造函数中初始化它。

        6
  •  1
  •   Joshua Pinter    6 年前

    当前线程的获取方式有:

    Thread t = Thread.currentThread();
    

    线程ID获取:

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

    线程名称获取:

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