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

我有一个固定的线程池,我提交任务(限于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? } } 

使用Thread.currentThread()

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

接受的答案回答有关获取线程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(); } } 

和输出:

 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 

使用模算术稍微调整一下就可以让你正确地执行“Y的X线程”:

 // 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 

你可以使用Thread.getCurrentThread.getId(),但是为什么当这个logging器pipe理的LogRecord对象已经拥有了线程Id的时候呢? 我认为你错过了一个configuration的地方,logging日志消息的线程ID。

如果你的类inheritance了Thread ,你可以使用方法getNamesetName命名每个线程。 否则,你可以添加一个name字段到MyTask ,并在你的构造函数中初始化它。

如果您正在使用日志logging,则线程名称将会很有帮助。 一个线程工厂帮助:

 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 
Interesting Posts