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

问题描述 投票:0回答:7

我有一个固定的线程池,我可以向其提交任务(仅限 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?
    }
}
java multithreading threadpool executorservice executors
7个回答
259
投票

使用

Thread.currentThread()

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

26
投票

接受的答案回答了有关获取 a 线程 id 的问题,但它不允许您执行“Thread X of 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

使用模算术进行轻微调整将允许您正确执行“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 

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,则可以使用方法

getName
setName
来命名每个线程。否则,您可以将
name
字段添加到
MyTask
,并在构造函数中初始化它。


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"

0
投票

getId
的方法
Thread.currentThread.getId()
自19起已被弃用。如果使用它会发出警告:

@Deprecated(since"19")

Deprecated

This method is not final and may be overriden to return a value that is not the thread ID. Use threadId() instead

推荐使用

Thread.currentThread.threadId()
© www.soinside.com 2019 - 2024. All rights reserved.