我有一个提交任务的固定线程池(仅限于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?
}
}
发布于 2010-07-21 04:59:17
使用Thread.currentThread()
private class MyTask implements Runnable {
public void run() {
long threadId = Thread.currentThread().getId();
logger.debug("Thread # " + threadId + " is doing this task");
}
}
发布于 2013-08-20 22:09:59
被接受的答案回答了关于获取线程id的问题,但它不允许您执行"Thread X of Y“消息。线程ids在线程之间是唯一的,但不一定从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
发布于 2010-07-21 05:04:12
您可以使用Thread.getCurrentThread.getId(),但是当记录器管理的LogRecord对象已经具有线程Id时,为什么还要这样做呢?我认为您在某处缺少记录日志消息的线程I的配置。
https://stackoverflow.com/questions/3294293
复制相似问题