views:

125

answers:

4

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.

+3  A: 

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?

James
Perhaps it is, let me know how that helps me.
FarmBoy
If you are refering to the ThreadPool Pattern, then go to the link and read up on why you would use it...If you mean regarding the array, then is it not obvious? You would add each thread into the array when you start them, and remove them when you destroy them. Hence you have an array of active threads. So if array.count = 1 then you know it is the last thread active.
James
OK, I'll use a list. I'm still curious if there is a way without the bookkeeping.
FarmBoy
Sorry, my first comment was made when I strangely hadn't noticed your second sentence.
FarmBoy
+10  A: 

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.

Zed
+1 I think this is what he is looking for.
James
+1 also like this solution. very elegant.
Nico
+1  A: 

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.

John Meagher
The ThreadGroup API is problematic.. see Josh Bloch's "Effective Java" for an example (search 'threadgroup effective java' on Google Books to see the page in question, URL is too long to paste here). The Enumerate method, for example, is not sensibly threadsafe (!). In this case you probably know how many Threads there are, so the array sizing problem Bloch describes probably won't be an issue, but it's still an odd API.
Cowan
A: 

Is using Executors and invokeAll an option? I.e. can you implement your functionality as Callables?

Then it is trivially simple to do.

Thorbjørn Ravn Andersen