• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Kill program once a thread has completed?

 
Ranch Hand
Posts: 285
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
reply
    Bookmark Topic Watch Topic
  • New Topic