Last week, we had the author of TDD for a Shopping Website LiveProject. Friday at 11am Ranch time, Steven Solomon will be hosting a live TDD session just for us. See for the agenda and registration link
Basically, the common recommendation is as follows:
1. Define some variable or flag, which indicates whether the thread should keep running, or whether it's been asked to stop . Initialize it to say 'keep runnig'. Your thread should keep checking this variable, from within its 'run' method. If asked to stop, you can use 'return', or just break any loops you're in.
Note this variable can be anything you want... you can use: - your own boolean flag where 'true' means 'run' and 'false' means 'stop' - some object-reference where 'null' means 'stop' and any other value means 'run' - the 'isInterrupted' flag, that's already built into all threads.
2. Whoever wishes to stop your thread, should set this variable to a value that means 'please stop'. It's also recommended to call 'interrupt', so that your thread is released from any sleep/wait conditions (otherwise, your thread will only stop when/if it wakes up).
Example (I chose to use the 'isInterrupted' flag as my 'variable') :
Now, you can call 'stopMe()' from the thread itself, like you did in your example:
But IMHO it makes more sense to call it from another thread...
Originally posted by shashi nela: Till java 1.3 it was stop() method which was killing the thread.
But as of java 1.4 this method has been deprecated.
No, it was deprecated much earlier than that. It must never be used. Neither may the other deprecated methods.
Basically, there is no magic way to stop a thread. You have to work out a way for your threads to co-operate, to achieve the behaviour you want. There are various patterns for this, some of which are mentioned in this thread; but, be careful as some of the stuff in this thread is wrong. Also, try STFW and also searching the archive of this JavaRanch topic.
Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.