interrupt()、interrupted()方法的使用和线程退出的时机

    当你在线程上调用interrupt()时,线程中断发生的唯一时刻是在任务要进入到可中断的阻塞操作(如sleep,wait, join等)中,或者已经在阻塞操作内部时。此时线程会抛出InterruptedException,并从异常中退出。如果run()方法内部恰巧没有可以产生阻塞的部分,则run()方法可能就无法被interrupt方法中断。此时,可以调用interrupted()方法判断线程的终止状态,并根据状态控制线程的中断。

 
  
package Concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class InterruptedClass implements Runnable {
@Override
public void run() {
double d = 0.0f ;
try {
while ( ! Thread.interrupted()) {
System.out.println(
" Running in InterrupedClass " );
// before sleep, point 1
Thread.sleep( 2000 );
// before calculating, point 2
System.out.println( " Calculating... " );
for ( int i = 0 ; i < 900000 ; i ++ ) {
d
= d + (Math.PI + Math.E) / d;
}
System.out.println(
" After calculating " );
}
}
catch (InterruptedException e) {
System.out.println(
" Exiting via InterruptedException " );
}
finally {
System.out.println(
" In finally! " );
}
}
}

public class Interrupt {

public static void main(String[] args) throws Exception {
ExecutorService exec
= Executors.newCachedThreadPool();
exec.execute(
new InterruptedClass());

Thread.sleep(
1000 ); // 如果睡眠1000ms,则在point1处之前就调用了shutdownNow,即调用了interrupt
// 因此再调用sleep方法时会抛出异常并从catch处退出

// Thread.sleep(2001); // 如果睡眠2001ms,则在point2处调用interrupt,即在正常运行处调用interrupt
// 因此会执行完循环中的大数计算,再词运行到while(!Thread.interrupted())处
// 时才回中断,退出while,不抛出异常

// finally或catch中可以添加释放占用资源的代码
exec.shutdownNow();
}

}

转载于:https://www.cnblogs.com/kadinzhu/archive/2011/04/15/2017557.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值