javamultithreadinginterrupted-exception

Java thread InterruptedException block not executing


My Java class is given below. It's a small exercise to test thread join (wait) and thread sleep (timed wait).

public class BasicThreadTest {

    public static void main(String[] args) {
        testThreadWait();
        System.out.println(Thread.currentThread().getName() + " exiting");
    }

    private static void testThreadWait() {
        Thread thread1 = new Thread(() -> {
            String currentThread = Thread.currentThread().getName();
            System.out.println(String.format("%s execution started", currentThread));
            long waitMillis = 20000L;
            try {
                System.out.println(String.format("%s going for timed wait of %d millis", currentThread, waitMillis));
                Thread.sleep(waitMillis);
            } catch (InterruptedException e) {
                System.out.println(String.format("%s timed wait over after %d millis", currentThread, waitMillis));
            }
            System.out.println(String.format("%s execution ending", currentThread));
        });
        thread1.setName("Thread-1");

        Thread thread2 = new Thread(() -> {
            String currentThread = Thread.currentThread().getName();
            System.out.println(String.format("%s execution started", currentThread));
            try {
                System.out.println(currentThread + " about to wait for " + thread1.getName());
                thread1.join();
            } catch (InterruptedException e) {
                System.out.println(String.format("%s wait over for %s", currentThread, thread1.getName()));
            }
            System.out.println(String.format("%s execution ending", currentThread));
        });
        thread2.setName("Thread-2");

        thread2.start();
        thread1.start();
    }
}

No matter what order I start the two threads in I never get the two InterruptedException blocks executed in either sleep() or join(). Below is a sample output:

Thread-2 execution started
Thread-2 about to wait for Thread-1
main exiting
Thread-1 execution started
Thread-1 going for timed wait of 20000 millis
Thread-1 execution ending
Thread-2 execution ending

Any explanation on why this is happening?


Solution

  • You won't get an InterruptedException if you don't actually interrupt the threads.

    You could try, for example:

        thread2.start();
        thread1.start();
        
        Thread.sleep(1000);
    
        thread1.interrupt();
        thread2.interrupt();
    

    Ideone demo

    Output:

    Thread-2 execution started
    Thread-1 execution started
    Thread-1 going for timed wait of 20000 millis
    Thread-2 about to wait for Thread-1
    Thread-1 timed wait over after 20000 millis
    Thread-1 execution ending
    Thread-2 wait over for Thread-1
    Thread-2 execution ending
    main exiting