Visualizzare tutti thread attivi in Kotlin

Mattepuffo's logo
Visualizzare tutti thread attivi in Kotlin

Visualizzare tutti thread attivi in Kotlin

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:

fun main() {
  val worker = Thread({
    try {
      Thread.sleep(5000)
    } catch (e: InterruptedException) {
      println(e.message)
    }
  }, "th1")
  worker.start()

  val worker2 = Thread({
    try {
      Thread.sleep(5000)
    } catch (e: InterruptedException) {
      println(e.message)
    }
  }, "th2")
  worker2.start()

  for (t in Thread.getAllStackTraces().keys) {
    println(t.name)
  }
}

Quindi se banalmente vogliamo cercare un thread per nome:

fun main() {
  val worker = Thread({
    try {
      Thread.sleep(5000)
    } catch (e: InterruptedException) {
      println(e.message)
    }
  }, "th1")
  worker.start()

  val worker2 = Thread({
    try {
      Thread.sleep(5000)
    } catch (e: InterruptedException) {
      println(e.message)
    }
  }, "th2")
  worker2.start()

  for (t in Thread.getAllStackTraces().keys) {
    if (t.name.equals("th1")) {
      println(t.name)
    }
  }
}

Enjoy!


Condividi

Commentami!