Stopping a thread in an Android Service
I have a Thread running in a Service... its run method looks something like this:
class Consumer implements Runnable {
public void run() {
while(!fin开发者_开发百科ished){
foo();
}
cleanUp();
}
...
}
I'm starting the thread in the onStartCommand
method of the service and I want to shut it down when the service stops. Now to stop the thread I'm setting the finished
variable to true
(in the service's onDestroy
method).
public void onDestroy() {
...
finished = true;
...
}
(turns out that it works just fine when I'm debugging the program -> cleanUp
will be called as expected)
Without debugging it, cleanUp
won't be called. Can anyone explain this to me? Where's my error? Thanks
Definitely a Thread synchronization issue since Debugger will serialize things for you and it works.
I would suggest using signaling to solve your problem.
One way is after setting isFinished=TRUE; do a wait(int timeout) and have the run loop (consumer class) to do notify();. This way even Consumer class is in bad state, you still get out after your timeout.
精彩评论