首页 > 解决方案 > Java线程InterruptedException块未执行

问题描述

下面给出了我的 Java 类。这是一个测试线程加入(等待)和线程睡眠(定时等待)的小练习。

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

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

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

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

标签: javamultithreadinginterrupted-exception

解决方案


wait()InterruptedException当块(或等待)完成时不抛出。

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


推荐阅读