Visualizzare tutti thread attivi in Java

Mattepuffo's logo
Visualizzare tutti thread attivi in Java

Visualizzare tutti thread attivi in Java

Supponiamo che nella nostra applicazione Java avviamo più Thread per svolgere determinate operazioni.

Ad un certo punto vogliamo vedere tutti quelli attivi.

Eccovi un esempio molto basico:

public class Main {
  public static void main(String[] args) {

    Thread worker = new Thread(() -> {
      try {
        Thread.sleep(5000);
      } catch (InterruptedException e) {
        System.out.println(e.getMessage());
      }
    }, "th1");
    worker.start();

    Thread worker2 = new Thread(() -> {
      try {
        Thread.sleep(5000);
      } catch (InterruptedException e) {
        System.out.println(e.getMessage());
      }
    }, "th2");
    worker2.start();

    for (Thread t : Thread.getAllStackTraces().keySet()) {
      System.out.println(t.getName());
    }

  }
}

Quindi se banalmente vogliamo cercare un thread per nome:

public class Main {
  public static void main(String[] args) {

    Thread worker = new Thread(() -> {
      try {
        Thread.sleep(5000);
      } catch (InterruptedException e) {
        System.out.println(e.getMessage());
      }
    }, "th1");
    worker.start();

    Thread worker2 = new Thread(() -> {
      try {
        Thread.sleep(5000);
      } catch (InterruptedException e) {
        System.out.println(e.getMessage());
      }
    }, "th2");
    worker2.start();

    for (Thread t : Thread.getAllStackTraces().keySet()) {
      if (t.getName().equals("th2")) {
        System.out.println(t.getName());
      }
    }

  }
}

Enjoy!


Condividi

Commentami!