Pregunta

Tengo un grupo de subprocesos fijo al que envío tareas (limitado a 5 hilos).¿Cómo puedo saber cuál de esos? 5 threads ejecuta mi tarea (algo así como "thread #3 of 5 está haciendo esta tarea")?

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?
    }
}
¿Fue útil?

Solución

utilizando Thread.currentThread():

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

Otros consejos

La respuesta aceptada responde a la pregunta sobre cómo obtener a ID de hilo, pero no le permite hacer "Hilo X de y" mensajes.Los ID de hilo son únicos a través de hilos, pero no necesariamente comienzan de 0 o 1.

Aquí hay un ejemplo que coincide con la 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();
  }
}

y la salida:

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

Un ligero modaje de ajuste con la aritmética de Modulo le permitirá hacer "Hilo X de Y" correctamente:

// modulo gives zero-based results hence the +1
long threadId = Thread.currentThread().getId()%numThreads +1;

Nuevos 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 

Puede usar hilos.getcurrentthread.getid (), pero ¿por qué querría hacer eso cuando Logregord Los objetos administrados por el registrador ya tienen el ID de hilo.Creo que le falta una configuración en algún lugar que registre las ID de hilo para sus mensajes de registro.

Si tu clase hereda de Hilo, puedes usar métodos getName y setName para nombrar cada hilo.De lo contrario, podrías simplemente agregar un name campo a MyTask, e inicialícelo en su constructor.

Si está utilizando el registro, entonces los nombres de los hilos serán útiles. Una fábrica de hilo ayuda con esto:

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

Salida:

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

Hay la forma de obtener el hilo actual:

Thread t = Thread.currentThread();

Después de tener un objeto de clase de hilo (t), puede obtener información que necesita con los métodos de clase de subprocesos.

ID de hilo Getting:

long tId = t.getId(); // e.g. 14291

Nombre de hilo Getting:

String tName = t.getName(); // e.g. "pool-29-thread-7"

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top