Search code examples
javamultithreadinginterrupt

Can one thread interrupts another thread?


I'm wondering whether it is illegal to interrupt another thread in the first thread's run method. If yes, when I invoke another thread's interrupt method in the first thread's run method, will a "InterruptedException" be thrown? Like this:

public static void main(String[] args) {

    Thread thread1 = new Thread(() -> {
        while (true) {

        }
    }, "thread1");
    try {
        thread1.sleep(10000);
    } catch (InterruptedException e) {
        System.out.println("Oops! I'm interrupted!"); 
    }
    Thread thread2 = new Thread(() -> {
        System.out.println("I will interrupt thread1!");
        thread1.interrupt();
        System.out.println("Thread1 interruption done!");
    }, "thread2");
    thread1.start();
    thread2.start();
}

But I got no message "Oops! I'm interrupted!" in the Console.


Solution

  • The reason your program doesn't work is that you are using the thread1 reference to access the static sleep() method, but the sleeping is still executed in the main thread.
    Move it into the body of thread1, and your program works fine:

    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                System.out.println("Oops! I'm interrupted!");
            }
        }, "thread1");
    
        Thread thread2 = new Thread(() -> {
            System.out.println("I will interrupt thread1!");
            thread1.interrupt();
            System.out.println("Thread1 interruption done!");
        }, "thread2");
        thread1.start();
        thread2.start();
    }
    

    This prints:

    I will interrupt thread1!
    Thread1 interruption done!
    Oops! I'm interrupted!
    

    Note that the order of the last two printouts depends on the thread scheduling, and may vary.