中断正在运行的线程

  Java提供了一种用于停止线程的协商机制一一中断,也即中断标识协商机制

  interrupt();//中断线程 将中断标志位置为true 由正在运行的程序自行判断是不是需要中断.注意此方法会中断 wait, join, sleep 的执行,将收到InterruptedException 且它的中断状态将被清除

isInterrupted();// 获取中断标志位。不清除中断标志位。上次调用返回true,接着调用还会返回true

Thread.interrupted();// 获取中断标志位,并且将清除中断标志位.将中断标志位置为false.

public class interruptDemo {
//执行过程中中断线程
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
for(;;){
if(Thread.currentThread().isInterrupted()){// 获取中断标志位
System.out.println(Thread.currentThread().getName()+"线程停止");
boolean res = Thread.interrupted();// 获取中断标志位,并且将清除中断标志位
System.out.println(res);// true
System.out.println(Thread.currentThread().isInterrupted());// false
break;
}
System.out.println(123);
}
}
});
t.start();

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t.interrupt();// 中断线程 将中断标志位置为true 由正在运行的程序自行判断是不是需要中断
}


}
posted @   yunmz  阅读(19)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示