开发者

Stopping a thread in an Android Service

开发者 https://www.devze.com 2023-04-02 00:57 出处:网络
I have a Thread running in a Service... its run method looks something like this: class Consumer implements Runnable {

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消