Stop a thread like:
new Thread ( new Runnable() {
public void run(){
if ( condition ) return; // this will stop the thread.
}
}).start();
is correct/safe?
condition
to be volatile if it's a variable being set from another thread. However, there's no indication in OP's question that condition
is being changed from another thread - Ted Hopp 2012-04-04 18:48
condition
(before the if statement), so I think the synchronization is not needed.. - amp 2012-04-04 20:31
A thread stops when it's run()
method returns. It doesn't really matter what logic is used inside run()
to decide when or how to return. Your code is perfectly correct and safe.
run()
method returns. It's certainly possible to write infinite loops or run afoul of inter-thread synchronization issues like you describe, but that just means that the run()
method may never return (and hence the thread will never stop). My answer does need an amendment, however: the thread will stop when the run()
method exits, even if it exits by throwing an exception instead of returning - Ted Hopp 2012-04-04 18:45
Thread
, which is different than letting a Thread
complete its task and end. If that's what OP wants to do, then why the condition? Maybe I'm just reading it incorrectly. I am truthfully trying to be helpful as I have seen this kind of asynchronous thread termination many times - sethro 2012-04-04 19:39
run()
method returns or abnormally ends (which is a direct answer to OP's question as I understood it) and the rules for correctly sharing data between threads - Ted Hopp 2012-04-04 20:33
Certainly. The Thread
will then finish and can be joined with. The thread would also exit if you threw a RuntimeException
or just let the code run off the end of the run()
method obviously.
Yes, it is correct and safe...