• Post Reply Bookmark Topic Watch Topic
  • New Topic

Kill program once a thread has completed?

 
Anthony Smith
Ranch Hand
Posts: 285
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a class that implements Runnable. The main method of this class just starts threads. When any of the threads complete, I want the program to stop. How do I do this?
 
Henry Wong
author
Sheriff
Posts: 22542
109
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Anthony Smith:
I have a class that implements Runnable. The main method of this class just starts threads. When any of the threads complete, I want the program to stop. How do I do this?


That's an interesting scenario. Most of the time, you would want a particular thread (or set of threads) to finish -- not when *any* thread in a group finish... but okay...

The best option is to modify the threads, to set some sort of DONE flag and notify the main thread, which is waiting. This main thread can then simply call System.exit().

Other option, is to have the main thread call join(), with a small timeout, in a loop, repeatedly on the threads. And call System.exit() if any of those don't return by timeout.

Henry
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can also modify the run() method to call System.exit(0); directly at the end of the thread. You may also use try / finally to ensure the exit occurs even if an exception is thrown. If that's what you want...
[ July 05, 2006: Message edited by: Jim Yingst ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!