Question

J'ai un pool de threads fixe auquel je soumets des tâches (limité à 5 fils).Comment puis-je savoir lequel de ces 5 threads exécute ma tâche (quelque chose comme "thread #3 of 5 fait cette tâche") ?

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?
    }
}
Était-ce utile?

La solution

En utilisant Thread.currentThread():

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

Autres conseils

La réponse acceptée répond à la question concernant l'identifiant de thread A , mais cela ne vous permet pas de "enfiler x de Y".Les identifiants de thread sont uniques à travers les threads mais ne commencent pas nécessairement à 0 ou 1.

Voici un exemple correspondant à la 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();
  }
}

et la sortie:

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 léger délice à l'aide de l'arithmétique modulo vous permettra de faire correctement "enfiler x de y":

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

nouveaux résultats:

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 

Vous pouvez utiliser thread.getCurrentThread.getid (), mais pourquoi voudriez-vous faire cela lorsque Logrecord Les objets gérés par l'enregistreur ont déjà l'ID de thread.Je pense que vous manquez une configuration quelque part qui enregistre les identifiants de thread pour vos messages de journal.

Si votre classe hérite de Fil, vous pouvez utiliser des méthodes getName et setName pour nommer chaque fil.Sinon, vous pouvez simplement ajouter un name champ à MyTask, et initialisez-le dans votre constructeur.

Si vous utilisez la journalisation, les noms de threads seront utiles. Une usine de fil aident avec ceci:

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

sortie:

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

Il y a le chemin du fil actuel:

Thread t = Thread.currentThread();

Après avoir obtenu un objet de classe de thread (t), vous pouvez obtenir des informations dont vous avez besoin en utilisant des méthodes de classe de thread.

ID de thread Gettingting:

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

Nom du fil Gettingting:

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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top