• Post Reply Bookmark Topic Watch Topic
  • New Topic

Stopping a continuosly executing Thread  RSS feed

 
A Kumar
Ranch Hand
Posts: 980
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

How can we stop a continously executing thread...

Suppose a thread has invoked the start method and in turn its run method has started executing...then

how to stop if this thread executes continously...?

Regards
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a frequently-asked question. It may even actually be in the JavaRanch FAQ.

Anyway, there is no safe way forcibly to stop another thread. You must not, however tempting it may seem, use the deprecated methods like Thread.stop(), because your application will foul-up (not every time you run it, but intermittently and confusingly).

You have to devise a way by which the threads of your application can co-operate, to decide when they should finish. Thread.interrupt() can be useful for that, or the threads may share some shut-down flag.

By the way, if all you want to do is stop a long-running thread at application shut-down, you may only need to make the long-running thread a daemon thread (using Thread.setDaemon()). Then it will automatically stop when all non-daemon threads have stopped.
[ June 30, 2006: Message edited by: Peter Chase ]
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving, not surprisingly, to "Threads and Synchronization."
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If your thread is in a loop, it's pretty easy to stop it at the next time around:

I used to use a boolean called "running" instead of checking for interrupted, but interrupted is more the spirit of things and actually behaves better. There are quite a few things that can be broken into by the interrupt() and you may want to wrap them in try-catch blocks. But there are plenty that can't. For example, if you're waiting on an unininterruptable blocking IO or you might wait a long time. That's when there is no good weay to kill a thread
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!