Java 线程 InterruptedException 块未执行

Java thread InterruptedException block not executing

我的Javaclass如下。测试thread join(wait)和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();
    }
}

无论我以什么顺序启动两个线程,我都不会在 sleep()join() 中执行两个 InterruptedException 块。以下是示例输出:

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

任何解释为什么会发生这种情况?

当块(或等待)完成时,

wait() 不会抛出 InterruptedException

如果您启动第三个调用 thread1.interrupt() 的线程,那么您将获得 InterruptedException.

如果您实际上没有中断线程,您将不会得到 InterruptedException

您可以尝试,例如:

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

    thread1.interrupt();
    thread2.interrupt();

Ideone demo

输出:

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