上篇总结了Thread的使用和原理,那么当我们需要终止一个线程执行,该如何处理呢?
stop()方法
终止一个线程执行,我们首先想到的是Thread有没有提供终止的函数,不负所望我们找到了stop()方法(删除方法),示例代码如下
Log.i("thread","test thread start");
TestThread testThread = new TestThread();
testThread.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
testThread.stop();
Log.i("thread","test thread interrupt");
public class TestThread extends Thread {
@Override
public void run() {
super.run();
while (true) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i("thread","test thread running");
}
}
}
执行上述的代码,中了彩蛋,抛出了UnsupportedOperationException,看看stop()方法的具体实现
@Deprecated
public final void stop() {
stop(new ThreadDeath());
}
@Deprecated
public final synchronized void stop(Throwable throwable) {
throw new UnsupportedOperationException();
}
没做任何处理,直接抛出异常。
为什么不再支持stop()方法呢?如果通过stop()方法从外部来终止线程,而线程内部的处理逻辑执行到某一步的时候被强制终止,而接下来的逻辑没有被执行,这就可能导致应用出现不稳定的情况,例如假设从网上下载一个图片,先保存到磁盘再进行显示,当线程将图片写入到磁盘时,被外部强制终止了,图片没有进行显示,如果必须显示图片之后才能执行某些操作,因为线程被外部终止而无法继续进行。因此,线程由外部调用强制终止可能会导致应用一些不可预知的问题,那么如果由线程内部主动终止线程(即run()方法执行完成)或者继续执行一些必须执行完的操作,然后再终止线程,这样就可以避免这些不可预知的错误,因而有了interrupt机制来。
interrupt机制
Thread有三个关于interrupt的函数:interrupt()、interrupted()和isInterrupted()。
interrupt():中断线程,将线程的中断状态设置为true,标记线程处于中断状态;
interrupted():检查当前线程是否已经中断。线程的中断状态 由该方法清除。换句话说,如果连续两次调用该方法,则第二次调用将返回 false(在第一次调用已清除了其中断状态之后,且第二次调用检验完中断状态前,当前线程再次中断的情况除外;
isInterrupted():检查当前线程是否已经中断,不会清除线程的中断状态;
interrupt()
interrupt()函数只是将线程状态标记为中断状态,但不会终止线程,线程还会继续执行;
Log.i("thread","test thread start");
TestThread testThread = new TestThread();
testThread.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
testThread.interrupt();
Log.i("thread","test thread interrupt");
public class TestThread extends Thread {
@Override
public void run() {
super.run();