Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Killing a parent thread  RSS feed

 
Sree kanth
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all

is it possible to kill a main thread before killing the threads which have been created in the main thread.
When the parent thread is killed, will it kill the child threads

Rgds
Sree
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A thread dies when the code it was running returns. There's no safe way to "kill" a thread - you must arrange for its code to exit.

The main thread can die before the program ends. This will not cause threads that it created to die.

The above assumes your threads are not "daemon" threads. If you don't know what that means, read up on it. Search the threads forum, for instance.
[ October 19, 2006: Message edited by: Peter Chase ]
 
Srikanth Raghavan
Ranch Hand
Posts: 389
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A good programming practice is that, we should never stop (kill) a thread or pause a thread using the pause() method.

The follow methods are deprecated in the Thread API:

stop()
pause()
resume()

These methods are considered harmful because they may introduce error-prone deadlocks.

Alternate approaches are available.

For example, to stop a thread you must always check for some status variable, execute your clean up code (like closing files or db connections) and then you must exit the run() method. Just for the sake of stoping the thread you should not throw a NullPointerException yourself. I know you won't do this anyway

Look at this thread, I presented a code that will do a graceful termination of a thread: Click here


Instead of pause() and resume(), you should be using wait() and notifyAll() mechanism. Please check for some Thread related tutorial in java.sun.com

Hope this helps,
Srikanth
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!