如何从线程池获取线程id?
-
18-09-2020 - |
题
我有一个固定的线程池,我提交任务(仅限于 5 线程)。我怎样才能找出其中的哪一个 5 线程执行我的任务(类似于"thread#3of 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?
}
}
解决方案
使用Thread.currentThread()
:
private class MyTask implements Runnable {
public void run() {
long threadId = Thread.currentThread().getId();
logger.debug("Thread # " + threadId + " is doing this task");
}
}
. 其他提示
已接受的答案答案有关获取 a 线程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
.
使用Modulo算术的轻微调整将允许您正确执行“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(),但是当 Logrecord 由记录器管理的对象已具有Thread ID。我认为您在某处丢失了对日志消息的线程ID的配置。
如果你的类继承自 线程, ,可以使用方法 getName
和 setName
来命名每个线程。否则你可以添加一个 name
场到 MyTask
, ,并在你的构造函数中初始化它。
如果使用日志记录,则线程名称将有用。 线程工厂有助于以下:
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
. 当前线程获得:
Thread t = Thread.currentThread();
.
获得了线程类对象(t),您可以使用Thread类方法获取所需的信息。
线程ID Getting:
long tId = t.getId(); // e.g. 14291
.
线程名称getting:
String tName = t.getName(); // e.g. "pool-29-thread-7"
. 不隶属于 StackOverflow