Java 螺纹可以';不要捕捉到异常的干扰
我已经阅读了第146页上的代码,并对以下代码进行了编码:Java 螺纹可以';不要捕捉到异常的干扰,java,multithreading,concurrency,Java,Multithreading,Concurrency,我已经阅读了第146页上的代码,并对以下代码进行了编码: class RethroableTask implements Runnable{ private static final ScheduledExecutorService cancelExec = Executors.newScheduledThreadPool(1); private Throwable t; public void run(){ try{
class RethroableTask implements Runnable{
private static final ScheduledExecutorService cancelExec =
Executors.newScheduledThreadPool(1);
private Throwable t;
public void run(){
try{
while(true){}
}catch(Throwable t){
this.t = t;
}
}
public static void main(String[] args){
RethroableTask task = new RethrowableTask();
final Thread taskThread = new Thread(task);
taskThread.start();
cancelExec.schedule(new Runnable(){
public void run(){
taskThread.interrupt();//i want taskThread can catch interruptedException
}
},1,TimeUnit.SECONDS);
}
}
我希望taskshread
将InterruptedException
捕获为Throwable
,实际上taskshread
是true
,但taskshread
从未捕获它。为什么?
我将而(true){}
替换为
try{
Thread.currentThread().sleep(1000);//a blocking method
}catch(InterruptedException e){
System.out.println("interruptedException");
Thread.currentThread().interrupt();
}
它进入catch只有当线程在中断时刻等待阻塞方法调用时才会抛出
InterruptedException
在所有其他情况下,线程必须检查自己的中断状态。如果要测试所编写的类,请在while循环中调用阻塞方法。与停止不同,中断是一种协作机制:在检查当前线程的中断标志后,某些代码必须显式抛出InterruptedException
。这可以是声明抛出InterruptedException
的JDK方法,例如Thread.sleep
,也可以是您自己的代码
使用
while (true) Thread.sleep(Integer.MAX_VALUE);
这将同时解决两个问题:
InterruptedException
非常好地解释了线程中断的协作基础。