스레드 풀에서 스레드 ID를 가져 오는 방법은 무엇입니까?
-
18-09-2020 - |
문제
나는 일정을 제출하는 고정 된 스레드 풀 ( 5 스레드로 제한)을 갖는다.어떤 5 스레드가 어떤 작업을 실행할 수 있는지 어떻게 실행할 수 있습니까? 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 스레드 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 스레드 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
를 사용하여 각 스레드의 이름을 지정할 수 있습니다.그렇지 않으면 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)가있는 후에 스레드 클래스 메소드를 사용하여 필요한 정보를 얻을 수 있습니다.
스레드 ID gettting :
long tId = t.getId(); // e.g. 14291
.
스레드 이름 gettting :
String tName = t.getName(); // e.g. "pool-29-thread-7"
.