原理介绍:使用interrupt来通知,而不是强制
核心:想要停止线程其实是如何运用interrupt来通知那个线程,以及被停止的线程如何配合。
我们作为想停止线程的一方,根本没有能力去强行停止。由于我们想要终端的是其他的线程,这个线程很有可能不是我们来写的,我们或许对这个正在运行的线程的业务逻辑根本就不熟悉,我们想让它停止,其实是希望他完成了一系列的保存、交接工作再停止,而不希望它立刻停止,使它陷入一种混乱的状态。被停止的线程本身,对于自己的业务逻辑是最熟悉的, 所以在设计的时候把停止的权利和步骤交给了被停止线程本身。这个就是一个设计的出发点。
正确的停止方法:interrupt
1、线程通常会在什么情况下停止呢?
当run方法中的所有代码都执行完毕。线程中有异常出现,但是没有捕获。
2、线程可能被阻塞
3、如果线程在每次迭代后都阻塞
4、如果while里面放try/catch,会导致中断失效
package threadcoreknowledge.stopthreads;
/**
* 描述: 如果while里面放try/catch,会导致中断失效
*/
public class CantInterrupt {
public static void main(String[] args) throws InterruptedException {
Runnable runnable = () -> {
int num = 0;
while (num <= 10000 && !Thread.currentThread().isInterrupted()) {
if (num % 100 == 0) {
System.out.println(num + "是100的倍数");
}
num++;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread thread = new Thread(runnable);
thread.start();
Thread.sleep(5000);
thread.interrupt();
}
}
原因
虽然我们利用了!Thread.currentThread().isInterrupted()
来检查是不是已经中断,但是好像毫无效果。之所以会产生这样的原因, 是因为java在这几sleep函数的时候,有这样的一个理念,一旦响应了中断 ,于是就会把线程的这个interrupt标记清除。也就是说在刚才的情况下,由于interrupt标记被清除,所以检查不到任何别中断的迹象,导致程序不能退出。
实际开发中两种最佳实践
优先选择传递中断
1、catch了InterruptedExcetion之后的优先选择:在方法签名中抛出异常 那么在run()就会强制try/catch
package threadcoreknowledge.stopthreads;
import threadcoreknowledge.createthreads.ThreadStyle;
/**
* 描述: 最佳实践:catch了InterruptedExcetion之后的优先选择:在方法签名中抛出异常 那么在run()就会强制try/catch
*/
public class RightWayStopThreadInProd implements Runnable {
@Override
public void run() {
while (true && !Thread.currentThread().isInterrupted()) {
System.out.println("go");
try {
throwInMethod();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
//保存日志、停止程序
System.out.println("保存日志");
e.printStackTrace();
}
}
}
private void throwInMethod() throws InterruptedException {
Thread.sleep(2000);
}
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new RightWayStopThreadInProd());
thread.start();
Thread.sleep(1000);
thread.interrupt();
}
}
不想或者无法传递:恢复中断
2、在catch子语句中调用Thread.currentThread().interrupt()来恢复设置中断状态,以便于在后续的执行中,依然能够检查到刚才发生了中断。回到刚才RightWayStopThreadInProd补上中断,让它跳出。
package threadcoreknowledge.stopthreads;
/**
* 描述:最佳实践2:在catch子语句中调用Thread.currentThread().interrupt()来恢复设置中断状态,以便于在后续的执行中,依然能够检查到刚才发生了中断
* 回到刚才RightWayStopThreadInProd补上中断,让它跳出
*/
public class RightWayStopThreadInProd2 implements Runnable {
@Override
public void run() {
while (true) {
if (Thread.currentThread().isInterrupted()) {
System.out.println("Interrupted,程序运行结束");
break;
}
reInterrupt();
}
}
private void reInterrupt() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new RightWayStopThreadInProd2());
thread.start();
Thread.sleep(1000);
thread.interrupt();
}
}
不应该屏蔽中断
响应中断的方法总结列表。
总结:为什么使用interrupt来停止线程,有什么好处?
被中断的线程拥有如何响应中断的权利,因为有些线程的某些代码是非常重要的,我们必须要得等待这些线程处理完之后,或者他们准备好之后,再由他们主动去终止,或者如果他们不想理会我们的中断,这也是非常ok的。我们不应该鲁莽的使用stop方法,而是使用interrupt方法发出一个信号,让他们自己去处理。 这样线程更加安全,数据的一致性也得到了保证。