void mySubTask(){try{sleep(delay)}catch(InterruptedException e){Thread.currentThread.interrupt();}
}这串代码是《java核心技术》中并发一节的。14.2中断线程,634页。当线程处于阻塞状态时,对其发送一个中断信号,会导致抛出InterruptedException异常。那么以上代码,在捕捉了这个异常后为什么还要对其设置中断状态呢?换句话说,这里设置中断状态,意义何在呢?
2 回答

慕勒3428872
TA贡献1848条经验 获得超6个赞
抛出异常后会清除中断标记位,调用Thread.currentThread.interrupt()重新设置中断状态,让调用方知道是由于中断才结束线程的。
比如你上面的代码,sleep响应了中断,当线程在seep中的时候,如果这个时候有中断的请求,就会抛出InterruptedException异常,并且清除中断状态,所以我们有时候需要再置为中断状态(其实就是需要保持这个中断状态)。
public class Test { public static int count = 0; public static void main(String[] args) throws InterruptedException { Thread th = new Thread(){ @Override public void run() { while(true){ if(Thread.currentThread().isInterrupted()){//(1) System.out.println("Thread Interrupted"); break; } System.out.println("invoking!!!"); try { Thread.sleep(10000); } catch (InterruptedException e) { System.out.println("Interruted When Sleep"); //抛出异常后会清除中断标记位,所以需要重新设置中断状态,让(1)出的代码可以检测到中断结束线程 Thread.currentThread().interrupt(); } } } }; th.start(); Thread.currentThread().sleep(1000); th.interrupt(); } } 打印结果: invoking!!! Interruted When Sleep Thread Interrupted
添加回答
举报
0/150
提交
取消