只是给线程设置中断状态,不执行操作。
线程实例的三个方法
interrupt()是给线程设置中断标志;
interrupted()是检测中断并清除中断状态;
isInterrupted()只检测中断。
坑:还有重要的一点就是interrupted()作用于当前线程,即使调用的时候是以其它线程调用的,都只会作用于当前线程。
interrupt()和isInterrupted()作用于此线程,即代码中调用此方法的实例所代表的线程。
MyThread类:
public class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("i="+(i+1));
if(this.isInterrupted()){
System.out.println("通过this.isInterrupted()检测到中断");
System.out.println("第一个interrupted()"+this.interrupted());
System.out.println("第二个interrupted()"+this.interrupted());
break;
}
}
System.out.println("因为检测到中断,所以跳出循环,线程到这里结束,因为后面没有内容了");
}
}
public class Do {
public static void main(String[] args ) throws InterruptedException {
MyThread myThread=new MyThread();
myThread.start();
myThread.interrupt();
//sleep等待一秒,等myThread运行完
Thread.currentThread().sleep(1000);
System.out.println("myThread线程是否存活:"+myThread.isAlive());
}
}
————————————————
版权声明:本文为CSDN博主「LZing_」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_39682377/article/details/81449451
评论区