Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 571
Eric Wilson Avatar asked Dec 07 '22 06:12

Eric Wilson


2 Answers

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.

like image 117
Zed Avatar answered Mar 08 '23 22:03

Zed


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?

like image 44
James Avatar answered Mar 08 '23 23:03

James