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

151

我有一个固定大小的线程池来提交任务(限制为5个线程)。如何找出这5个线程中哪一个执行了我的任务(类似于"第3个线程中的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个回答

257

使用Thread.currentThread()

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

3
这并不是期望中的答案,应该使用“% numThreads”代替。 - petrbel
2
@petrbel他完美地回答了问题标题,并且在我的观点中,线程ID足够接近,当OP请求“类似于'5个线程中的第3个”的东西时。 - CorayThan
3
请注意,getId() 的示例输出为 14291,而 getName() 则提供了更有用的信息,例如 pool-29-thread-7 - Joshua Pinter

26

被接受的答案回答了如何获取线程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 

9
Java 线程 ID 是否保证连续?如果不是,那么您的取模运算将不能正确工作。 - Rag
@BrianGordon 不确定是否有保证,但代码似乎只是增加一个内部计数器:http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/lang/Thread.java#l217 - Burhan Ali
11
如果同时初始化了两个线程池,其中一个线程池中的线程可能会具有诸如1、4、5、6、7等ID,这种情况下你将有两个不同的线程显示相同的“我是5个线程中的第n个”消息。 - Rag
@BrianGordon Thread.nextThreadID() 是同步的,所以这不会成为问题,对吧? - Matheus Azevedo
1
@MatheusAzevedo 这与此无关。 - Rag

6
你可以使用Thread.getCurrentThread.getId(),但是为什么要这样做呢?因为由日志记录器管理的LogRecord对象已经有线程ID了。我认为你可能缺少某个配置,以记录线程ID用于日志消息。

3

如果您正在使用日志记录,则线程名称将非常有帮助。线程工厂可以帮助实现这一点:

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

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

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"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接