Programing

스레드 풀에서 스레드 ID를 얻는 방법은 무엇입니까?

lottogame 2020. 7. 6. 07:49
반응형

스레드 풀에서 스레드 ID를 얻는 방법은 무엇입니까?


작업을 제출하는 고정 스레드 풀이 있습니다 ( 5 개 스레드로 제한됨 ). 5 개의 스레드 중 어느 것이 내 작업을 실행 하는지 어떻게 알 수 있습니까 ( " 5 번 스레드 # 3 / 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 를 얻는 방법 에 대한 질문에 답변 하지만 "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

모듈로 산술을 사용하여 약간 조정하면 "스레드 X의 Y"를 올바르게 수행 할 수 있습니다.

// 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 

You can use Thread.getCurrentThread.getId(), but why would you want to do that when LogRecord objects managed by the logger already have the thread Id. I think you are missing a configuration somewhere that logs the thread Ids for your log messages.


If your class inherits from Thread, you can use methods getName and setName to name each thread. Otherwise you could just add a name field to MyTask, and initialize it in your constructor.


If you are using logging then thread names will be helpful. A thread factory helps with this:

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++);
    }
}

Output:

[   My thread # 0] Main         INFO  A pool thread is doing this task

There is the way of current thread getting:

Thread t = Thread.currentThread();

After you have got Thread class object (t) you are able to get information you need using Thread class methods.

Thread ID gettting:

long tId = t.getId();

Thread name gettting:

String tName = t.getName();

참고URL : https://stackoverflow.com/questions/3294293/how-to-get-thread-id-from-a-thread-pool

반응형