How can you check if a thread is the only remaining thread in Java?

I want the thread in the Java program to loop until all other threads disappear, and then end the loop. How can I find out when the loop thread remains the only remaining?

In my situation, the loop thread will not reference any other threads, so I don't think that isAlive() helps me.

+4
source share
5 answers

This may or may not help, depending on your use case.

Set the loop thread to daemon mode

 setDaemon(true); 

and Java will kill it for you if all non-daemon threads disappear.

+11
source

Will there be a situation when you consider the pool pool template ?

If not, is it not better to maintain a list of active threads, deleting them as they are destroyed?

+3
source

ThreadGroup has the methods you need. This will be easiest if you can create all threads in the same ThreadGroup, but this is not necessary. Thread.currentThread (). GetThreadGroup () will launch you. The enumeration methods in ThreadGroup is how you can get a list of all threads.

+1
source

Uses the Executors and invokeAll parameter? That is, can you implement your functionality as Callables?

Then it’s trivial to just do it.

0
source

You can hack something together using ThreadFactory, and just be sure to register all the threads in the WeakHashMap file.

Scroll the map to see which streams are alive.

Another possible approach - use ThreadJMXBean?

0
source

All Articles