views:

48

answers:

2

I would like to stop a thread in mid execution. From reading around, I am of the thought I will have to check a local variable to determine if the thread should continue or clean up and exit run(). Any ideas of cleanly implementing this?

+1  A: 

You could use the interrupt method. You could do some clean up before exiting the thread. A simple tutorial is here

codeplay
The interrupt method isn't enough. For example, if a thread is sending a file via ftp that is large(4GB), calling interrupt from another thread does nothing, till the thread is blocking.
NullPointer0x00
You could use isInterrupted() or interrupted() (resets the status flag) to see if it's interrupted. Maybe a hybrid of both approaches is needed in some scenarios.
codeplay
@NullPointer0x00 the long duration operation will be a problem for both interrupt and the boolean variable. A combination of both approaches may be better at attracting the attention of the thread. Of course, it depends on what the thread is supposed to be doing.
Bill Michell
+1  A: 

Often a way to do this is create a boolean volatile member variable, perhaps called "stopThread". The thread periodically polls this variable to see if it should terminate.

seand
Thanks, that is what I think I will do. I made a boolean variable called 'resume'. I like 'stopThread', I will have to make sure I do proper clean up.
NullPointer0x00
It is important to note the "volatile" keyword mentioned in the answer. Without it, there is no guarantee that any change to the value of the boolean will ever be visible to the thread in question.
Bill Michell