I am trying to understand multithreading and below is a program i was trying out. The output is however something i was not expecting. The thread prints another string from the array after it has been interrupted. Could someone please explain why this is happening even though the catch block is executed after interrupt.
Source Code:
package threads;
class Task implements Runnable {
String[] matrix = {
"Wubba lubba",
"dub dub",
"Avadra kadabra",
"lumos"
};
@Override
public void run() {
for (int i=0;i< matrix.length;i++){
try {
System.out.println(matrix[i]);
Thread.sleep(4000);
} catch (InterruptedException e) {
System.out.println("Thread interrupted: "+this);
//throw new RuntimeException(e);
}
}
}
}
public class Threads{
public static void main(String[] args) {
long patience = 8000;
Thread t = new Thread(new Task());
long startTime = System.currentTimeMillis();
t.start();
System.out.println("Started at: "+startTime);
while (t.isAlive()) {
try {
t.join(1000);
if ((System.currentTimeMillis() - startTime) > patience && t.isAlive()) {
t.interrupt();
t.join();
}
}
catch (InterruptedException e) {
//throw new RuntimeException(e);
System.out.println("Thread interrupted: ");
}
System.out.println("isAlive() ? "+t.isAlive());
}
System.out.println("Exiting");
}
}