How to get thread id from a thread pool?
Using Thread.currentThread()
:
private class MyTask implements Runnable { public void run() { long threadId = Thread.currentThread().getId(); logger.debug("Thread # " + threadId + " is doing this task"); }}
The accepted answer answers the question about getting a thread id, but it doesn't let you do "Thread X of Y" messages. Thread ids are unique across threads but don't necessarily start from 0 or 1.
Here is an example matching the question:
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(); }}
and the output:
burhan@orion:/dev/shm$ javac ThreadIdTest.java && java ThreadIdTestI am thread 8 of 5I am thread 9 of 5I am thread 10 of 5I am thread 8 of 5I am thread 9 of 5I am thread 11 of 5I am thread 8 of 5I am thread 9 of 5I am thread 10 of 5I am thread 12 of 5
A slight tweak using modulo arithmetic will allow you to do "thread X of Y" correctly:
// modulo gives zero-based results hence the +1long threadId = Thread.currentThread().getId()%numThreads +1;
New results:
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.