[英]How to get thread id from a thread pool?
我有一個固定的線程池,我提交任務(限於5個線程)。 如何找出這5個線程中的哪一個執行我的任務(類似“線程#3 of 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");
}
}
接受的答案回答了關於獲取線程 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
您可以使用Thread.getCurrentThread.getId(),但是當記錄器管理的LogRecord對象已經具有線程Id時,您為什么要這樣做? 我認為你缺少一個記錄日志消息的線程ID的配置。
如果您的類繼承自Thread ,則可以使用方法getName
和setName
來命名每個線程。 否則,您只需向MyTask
添加一個name
字段,並在構造函數中初始化它。
如果您正在使用日志記錄,那么線程名稱將很有幫助。 一個線程工廠幫助這個:
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();
獲得Thread類對象(t)后,您可以使用Thread類方法獲取所需的信息。
線程ID gettting:
long tId = t.getId();
線程名稱gettting:
String tName = t.getName();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.