Stopping/Destroying a Thread

2019-01-14 16:00发布

I have a Service that launches a Thread and a Runnable like so.

t = new Thread(new Runnable() {
    public void run() {
        doSomething();
    }
});

t.start();

The reason for the thread is to perform an Async task doSomething(). For now lets not worry about the other class AsyncTask. I have tried it and it does not work for my case. Edit: I can't use AsyncTask because it is meant for the UI thread only. This piece of code has to operate inside a Service, so nope, no AsyncTask :(

doSomething() contains some external libs so the issue I am having is that it can potentially be hung at one of the commands, without return any value (hence no error checking can even be done)

To work around this, I will want to, at some point of time, destroy the Service.

stopService(new Intent("net.MyService.intent));

This works fine and is easily verified on the phone. However, the Thread which was created above will continue to run even when the Service that spawned it is destroyed.

I am thus looking for the correct commands to insert in the Service's onDestroy() which will clean up the Thread for me.

t.destroy();
t.stop();

are both depreciated and cause application crashes.

I took this code from somewhere

@Override
public void onDestroy() {

    Thread th = t;
    t = null;

    th.interrupt();

    super.onDestroy();
}

but it still does not work, the thread continues to run. Any help guys?

7条回答
Fickle 薄情
2楼-- · 2019-01-14 16:54

Did you check the Java Thread Primitive Deprecation Documentation which is referenced in the Thread API JavaDoc. You will find some hints to handle your problem.

查看更多
登录 后发表回答