Reputation: 59405
I want a thread in a Java program to loop until all other threads die, and then end the loop. How can I know when my loop thread is the only thread remaining?
In my situation, the loop thread will have no reference to any other threads, so I don't think isAlive()
helps me.
Upvotes: 4
Views: 385
Reputation: 16520
You can hack something together by using a ThreadFactory and just be sure to register all threads in a WeakHashMap.
Iterate through the map to see which threads are alive.
Another possible approach - use a ThreadJMXBean?
Upvotes: 0
Reputation: 75426
Is using Executors and invokeAll an option? I.e. can you implement your functionality as Callables?
Then it is trivially simple to do.
Upvotes: 0
Reputation: 24778
ThreadGroup has the methods you need. It will be easiest if you can create all the threads in the same ThreadGroup, but that's not really necessary. Thread.currentThread().getThreadGroup() will get you started. The enumerate methods on ThreadGroup are how you can get the list of all the threads.
Upvotes: 1
Reputation: 57678
This might or might not help, depending on your use-case.
Set your loop thread to daemon mode
setDaemon(true);
and Java will kill it for you if all the non-daemon threads are gone.
Upvotes: 11
Reputation: 82136
Would this not be a situation where you would consider the Thread Pool Pattern?
If not, would it not be better to maintain a list of active threads, removing each as they are destroyed?
Upvotes: 3