中断正在运行的线程

  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 @ 2023-02-17 18:07  yunmz  阅读(16)  评论(0编辑  收藏  举报