Java并发编程(2):线程中断(含代码)

使用interrupt()中断线程

当一个线程运行时,另外一个线程能够调用对应的Thread对象的interrupt()方法来中断它,该方法只是在目标线程中设置一个标志,表示它已经被中断,并当即返回。这里须要注意的是,若是只是单纯的调用interrupt()方法,线程并无实际被中断,会继续往下执行。sql

下面一段代码演示了休眠线程的中断:架构

public class SleepInterrupt extends Object implements Runnable{
 public void run(){
 try{
 System.out.println("in run() - about to sleep for 20 seconds");
 Thread.sleep(20000);
 System.out.println("in run() - woke up");
 }catch(InterruptedException e){
 System.out.println("in run() - interrupted while sleeping");
 //处理完中断异常后,返回到run()方法人口,
 //若是没有return,线程不会实际被中断,它会继续打印下面的信息
 return; 
 }
 System.out.println("in run() - leaving normally");
 }
 
 public static void main(String[] args) {
 SleepInterrupt si = new SleepInterrupt();
 Thread t = new Thread(si);
 t.start();
 //主线程休眠2秒,从而确保刚才启动的线程有机会执行一段时间
 try {
 Thread.sleep(2000); 
 }catch(InterruptedException e){
 e.printStackTrace();
 }
 System.out.println("in main() - interrupting other thread");
 //中断线程t
 t.interrupt();
 System.out.println("in main() - leaving");
 }
}

运行结果以下:并发

主线程启动新线程后,自身休眠2秒钟,容许新线程得到运行时间。新线程打印信息“about to sleep for 20 seconds”后,继而休眠20秒钟,大约2秒钟后,main线程通知新线程中断,那么新线程的20秒的休眠将被打断,从而抛出InterruptException异常,执行跳转到catch块,打印出“interrupted while sleeping”信息,并当即从run()方法返回,而后消亡,而不会打印出catch块后面的“leaving normally”信息。分布式

请注意:因为不肯定的线程规划,上图运行结果的后两行可能顺序相反,这取决于主线程和新线程哪一个先消亡。但前两行信息的顺序一定如上图所示。高并发

另外,若是将catch块中的return语句注释掉,则线程在抛出异常后,会继续往下执行,而不会被中断,从而会打印出”leaving normally“信息。性能

待决中断

在上面的例子中,sleep()方法的实现检查到休眠线程被中断,它会至关友好地终止线程,并抛出InterruptedException异常。另一种状况,若是线程在调用sleep()方法前被中断,那么该中断称为待决中断,它会在刚调用sleep()方法时,当即抛出InterruptedException异常。学习

下面的代码演示了待决中断:spa

 

public class PendingInterrupt extends Object {
 public static void main(String[] args){
 //若是输入了参数,则在mian线程中中断当前线程(亦即main线程)
 if( args.length > 0 ){
 Thread.currentThread().interrupt();
 } 
 //获取当前时间
 long startTime = System.currentTimeMillis();
 try{
 Thread.sleep(2000);
 System.out.println("was NOT interrupted");
 }catch(InterruptedException x){
 System.out.println("was interrupted");
 }
 //计算中间代码执行的时间
 System.out.println("elapsedTime=" + ( System.currentTimeMillis() - startTime));
 }
}

若是PendingInterrupt不带任何命令行参数,那么线程不会被中断,最终输出的时间差距应该在2000附近(具体时间由系统决定,不精确),若是PendingInterrupt带有命令行参数,则调用中断当前线程的代码,但main线程仍然运行,最终输出的时间差距应该远小于2000,由于线程还没有休眠,便被中断,所以,一旦调用sleep()方法,会当即打印出catch块中的信息。执行结果以下:命令行

欢迎工做一到五年的Java工程师朋友们加入Java架构开发
: 867748702
群内提供免费的Java架构学习资料(里面有高可用、高并发、高性能及分布式、
Jvm性能调优、Spring源码,MyBatis,Netty,Redis,Kafka,Mysql,Zookeeper,
Tomcat,Docker,Dubbo,Nginx等多个知识点的架构资料)
合理利用本身每一分每一秒的时间来学习提高本身,
不要再用"没有时间“来掩饰本身思想上的懒惰!趁年轻,使劲拼,给将来的本身一个交代!线程

这种模式下,main线程中断它自身。除了将中断标志(它是Thread的内部标志)设置为true外,没有其余任何影响。线程被中断了,但main线程仍然运行,main线程继续监视实时时钟,并进入try块,一旦调用sleep()方法,它就会注意到待决中断的存在,并抛出InterruptException。因而执行跳转到catch块,并打印出线程被中断的信息。最后,计算并打印出时间差。

使用isInterrupted()方法判断中断状态

能够在Thread对象上调用isInterrupted()方法来检查任何线程的中断状态。这里须要注意:线程一旦被中断,isInterrupted()方法便会返回true,而一旦sleep()方法抛出异常,它将清空中断标志,此时isInterrupted()方法将返回false。

下面的代码演示了isInterrupted()方法的使用:

 

public class InterruptCheck extends Object{
 public static void main(String[] args){
 Thread t = Thread.currentThread();
 System.out.println("Point A: t.isInterrupted()=" + t.isInterrupted());
 //待决中断,中断自身
 t.interrupt();
 System.out.println("Point B: t.isInterrupted()=" + t.isInterrupted());
 System.out.println("Point C: t.isInterrupted()=" + t.isInterrupted());
 
 try{
 Thread.sleep(2000);
 System.out.println("was NOT interrupted");
 }catch( InterruptedException x){
 System.out.println("was interrupted");
 }
 //抛出异常后,会清除中断标志,这里会返回false
 System.out.println("Point D: t.isInterrupted()=" + t.isInterrupted());
 }
}

运行结果以下:

使用Thread.interrupted()方法判断中断状态

可使用Thread.interrupted()方法来检查当前线程的中断状态(并隐式重置为false)。又因为它是静态方法,所以不能在特定的线程上使用,而只能报告调用它的线程的中断状态,若是线程被中断,并且中断状态尚不清楚,那么,这个方法返回true。与isInterrupted()不一样,它将自动重置中断状态为false,第二次调用Thread.interrupted()方法,老是返回false,除非中断了线程。

以下代码演示了Thread.interrupted()方法的使用:

 

public class InterruptReset extends Object {
 public static void main(String[] args) {
 System.out.println(
 "Point X: Thread.interrupted()=" + Thread.interrupted());
 Thread.currentThread().interrupt();
 System.out.println(
 "Point Y: Thread.interrupted()=" + Thread.interrupted());
 System.out.println(
 "Point Z: Thread.interrupted()=" + Thread.interrupted());
 }

}

运行结果以下:

从结果中能够看出,当前线程中断自身后,在Y点,中断状态为true,并由Thread.interrupted()自动重置为false,那么下次调用该方法获得的结果即是false。

补充

这里补充下yield和join方法的使用。

join方法用线程对象调用,若是在一个线程A中调用另外一个线程B的join方法,线程A将会等待线程B执行完毕后再执行。

yield能够直接用Thread类调用,yield让出CPU执行权给同等级的线程,若是没有相同级别的线程在等待CPU的执行权,则该线程继续执行。

相关文章
相关标签/搜索