0

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");
    }
}

Output: enter image description here

Shivam...
  • 409
  • 1
  • 8
  • 21
  • The first duplink explains how thread interrupts work in general. The second one specifically covers the mistake that you have made ... albeit that your example is unrealistic. I doubt that a real application would use `sleep` like. – Stephen C Feb 26 '23 at 14:28

0 Answers0