El aceptou responder Responder a pregunta sobre como obter un ID de fío pero non o fai Deixe-lo facer o “fío X e” as mensaxes. O fío dos identificadores é único a través dos fíos, pero non necesariamente comezar 0 ou 1.
Aquí tes un exemplo de coincidencia da pregunta:
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(); }}
e o resultado:
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
Un lixeiro axuste usando un módulo aritmético permitirá que faga o “fío X e” correctamente:
// modulo gives zero-based results hence the +1long threadId = Thread.currentThread().getId()%numThreads +1;
Novos resultados:
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