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


131

我有一个固定的线程池,我可以将任务提交给该线程池(限制为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?
    }
}

Answers:


230

使用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 2014年

2
@petrbel他正在完美地回答问题标题,并且在我看来,当OP请求“类似于'线程#3之5”时,线程ID足够接近。
CorayThan 2015年

请注意,输出的示例getId()14291where getName()给您的pool-29-thread-7,我认为这会更有用。
约书亚·品特

26

接受的答案回答了关于获取问题一个线程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 

5
是否保证Java线程ID是连续的?如果不是,您的模将无法正常工作。
Brian Gordon

@BrianGordon不知道有关的保证,但代码似乎没有什么比递增内部计数器:hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/...
伯汉·阿里

6
因此,如果同时初始化两个线程池,则其中一个线程池中的线程可能具有例如1、4、5、6、7的ID,在这种情况下,您将拥有两个不同的线程,且它们具有相同的“我是线程n of 5“消息。
Brian Gordon

@BrianGordon Thread.nextThreadID()已同步,所以这不是问题,对吧?
Matheus Azevedo

@MatheusAzevedo与它无关。
布赖恩·戈登

6

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


1

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


1

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

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 t = Thread.currentThread();

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

线程ID获取:

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

线程名称获取:

String tName = t.getName(); // e.g. "pool-29-thread-7"
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.