I made a simple function to test interrupt()
& InterruptedException
in Java:
public static void main(String[] args) {
checkInterrupt();
}
private static void checkInterrupt() {
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();
}
}
}
};
Thread workingThread = new Thread(runMe);
System.out.println("workingThread("+workingThread.getId()+") interrupted 1 ? "+workingThread.isInterrupted());
workingThread.start();
try {
workingThread.join();
} catch (InterruptedException e) {
//I thought I should get InterruptedException, but I didn't, why?
System.out.println("workingThread("+workingThread.getId()+") is interrupted.");
}
System.out.println("workingThread("+workingThread.getId()+") interrupted 2 ? "+workingThread.isInterrupted());
}
As you see above, in run(), I interrupt the working thread by invoking Thread.currentThread().interrupt()
when i==3
. I thought my code should catch InterruptedException
during workingThread.join()
. But there is no exception at all. Why?
You'll get an InterruptedException
if the thread calling join
is interrupted while waiting for the other one to die. That's not what happens in your case - you're interrupting the thread you're joining which is an entirely different matter.
See more on this question at Stackoverflow