Pergunta

Eu tenho um fixo pool de threads que eu enviar tarefas para (limitado a 5 threads).Como posso saber que um desses 5 threads executa a minha tarefa (algo como "thread #3 5 está fazendo esta tarefa")?

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

Solução

Usando Thread.currentThread():

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

Outras dicas

Aceito resposta responde à pergunta sobre a obtenção de um id do thread, mas não deixar de fazer "Thread X de Y" mensagens.Thread ids são exclusivos segmentos, mas não, necessariamente, começar do 0 ou 1.

Aqui está um exemplo de correspondência a pergunta:

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 a saída:

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

Uma ligeira ajustar usando o módulo aritmético vai permitir que você faça "thread X de Y" corretamente:

// modulo gives zero-based results hence the +1
long 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 

Você pode usar Thread.getCurrentThread.getId(), mas por que você iria querer fazer isso quando LogRecord objetos gerenciados pelo logger de já ter o Id do thread.Eu acho que está faltando uma configuração em algum lugar que faz a thread Ids de mensagens de log.

Se a sua classe herda de Thread, você pode usar métodos getName e setName para o nome de cada segmento.Caso contrário, você pode simplesmente adicionar um name campo MyTask, e inicializá-lo em seu construtor.

Se você estiver usando o log, em seguida, o thread de nomes vai ser útil.Um thread fábrica de ajuda com este:

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

Saída:

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

Não é o caminho da thread atual obter:

Thread t = Thread.currentThread();

Depois você tem a classe Thread do objeto (t) você é capaz de obter informações de que você precisa usando Thread métodos de classe.

ID do Thread gettting:

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

Nome do Thread gettting:

String tName = t.getName(); // e.g. "pool-29-thread-7"
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top