我正在使用以下测试代码测试 InterruptedException:
Runnable runMe = new Runnable() {
@Override
public void run() {
for(int i=0; i<6; i++) {
System.out.println("i = "+i);
if(i==3) {
System.out.println("i==3, Thread = "
+Thread.currentThread().getId());
//I invoke interrupt() on the working thread.
Thread.currentThread().interrupt();
try {
Thread.currentThread().join();
} catch (InterruptedException e) {
//I caught InterruptedException
System.out.println(Thread.currentThread().getId()
+ " is interrupted!");
Thread.currentThread().interrupt();
}
}
}
}
};
Thread workingThread = new Thread(runMe);
workingThread.start();
try {
workingThread.join();
} catch (InterruptedException e) {
//Swallow
}
//the following log shows me workingThread.isInterrupted() is false, why?
System.out.println("workingThread("
+ workingThread.getId()+") interrupted ? "
+ workingThread.isInterrupted());
在run()
,我interrupt()
当前的工作线程,并抓住了一个InterruptedException
.
在主线程中,我的最后一行代码是System.out.println(...)
打印出工作线程的中断状态的代码。既然我陷入InterruptedException
了run()
,我虽然应该得到正确的信息workingThread.isInterrupted()
,但我得到了错误的信息,为什么?