javamultithreadingthreadpoolexecutorserviceexecutors

How to get thread id from a thread pool?


I have a fixed thread pool that I submit tasks to (limited to 5 threads). How can I find out which one of those 5 threads executes my task (something like "thread #3 of 5 is doing this task")?

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?
    }
}

Solution

  • Using Thread.currentThread():

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