中断机制之通过interrupt实现线程中断停止
如何停止中断运行中的线程?
首先,一个线程不应该由其他线程来强制中断或停止,而是应该由线程自己自行停止,自己来决定自己的命运,所以,Thread.stop,Thread.suspend,Thread.resume都已经被废弃了
interrupt实现线程中断停止
用isInterrupted 判断当前线程是否被中断 ,用interrupt()设置线程中断状态
package com.kwfruit.thread.interruptdemo;
import java.util.concurrent.TimeUnit;
public class Interruptdemo {
static volatile boolean isStop = false;
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
while (true) {
/**
* public boolean isInterrupted()
* 实例方法
* 判断当前线程是否被中断(通过检查中断标志位)
*/
if (Thread.currentThread().isInterrupted()) {
System.out.println(Thread.currentThread().getName() + "\t isStop被修改为true 程序停止");
break;
}
System.out.println("t1 --------hello interrupt api");
}
}, "t1");
t1.start();
System.out.println("t1 的默认中断标志为 "+t1.isInterrupted());
try {
TimeUnit.MICROSECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
/**
* public void interrupt()
* 实例方法 Just to set the interrupt flag
* 实例方法仅仅是设置线程的中断状态为true,发起一个协商而不会立刻停止线程
*/
t1.interrupt();
},"t2").start();
}
}
t1 的默认中断标志为 false
t1 --------hello interrupt api
t1 --------hello interrupt api
t1 --------hello interrupt api
t1 --------hello interrupt api
t1 isStop被修改为true 程序停止
Process finished with exit code 0
本文作者:KwFruit
本文链接:https://www.cnblogs.com/mangoubiubiu/p/17977934
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
2021-01-21 JSR 303 表单校验(一)
2021-01-21 element ui 表单校验(vue)
2021-01-21 layui表单校验