首页 > 其他 > 详细

interrupt、interrupted和isInterrupted

时间:2020-08-13 10:25:15      阅读:44      评论:0      收藏:0      [点我收藏+]

interrupt()

其作用是中断此线程(此线程不一定是当前线程,而是指调用该方法的Thread实例所代表的线程),但实际上只是给线程设置一个中断标志,线程仍会继续运行。

该方法经常用来“吵醒休眠的线程“。 当一些线程调用sleep() 方法处于休眠状态时,一个占有CPU资源的线程可以让休眠的线程调用interrupt()方法“吵醒”自己。即导致休眠的线程发火说呢过InterruptException异常,从而结束休眠,重新排队等待CPU资源

 

interrupted()

作用是测试当前线程是否被中断(检查中断标志),返回一个boolean并清除中断状态,第二次再调用时中断状态已经被清除,将返回一个false。

 

isInterrupted ()

作用是只测试此线程是否被中断 ,不清除中断状态。

 

如:

public class Threadinterrup extends Thread {

public void run() {

for (int i = 0; i < 10; i++) {

// try {
// System.out.println("**********************in run()-这个线程休眠20秒");
// Thread.sleep(20000);
// System.out.println("**********************in run-继续进行!");
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
System.out.println("结果:"+(i+1));

}

}

}
public class ThreadinterrupText {



public static void main(String[] arg)
{

Threadinterrup threadtest=new Threadinterrup();

Thread thread=new Thread(threadtest);
thread.start(); //启动 n 个线程
//但实际上只是给线程设置一个中断标志
thread.interrupt();

//作用是只测试此线程是否被中断 ,不清除中断状态
System.out.println("第一次调用thread.isInterrupted():"+thread.isInterrupted());

System.out.println("第二次调用thread.isInterrupted():"+thread.isInterrupted());

//作用是测试当前线程是否被中断(检查中断标志)
System.out.println("第三次调用thread.interrupted():"+thread.interrupted());

System.out.println("thread是否存活:"+thread.isAlive());

}
}

结果:

第一次调用thread.isInterrupted():true
第二次调用thread.isInterrupted():true
第三次调用thread.interrupted():false
thread是否存活:true
结果:1
结果:2
结果:3
结果:4
结果:5
结果:6
结果:7
结果:8
结果:9
结果:10

interrupt、interrupted和isInterrupted

原文:https://www.cnblogs.com/shu-java-net/p/13494591.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!