java线程中断异常块未执行

8mmmxcuj  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(395)

下面给出了我的java类。这是一个测试线程连接(wait)和线程睡眠(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();
    }
}

不管我以什么顺序开始这两个线程,我永远也得不到这两个线程 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

为什么会这样?

zwghvu4y

zwghvu4y1#

wait() 不抛出 InterruptedException 当阻塞(或等待)结束时。
如果启动第三个线程 thread1.interrupt() 然后你会得到 InterruptedException .

omhiaaxx

omhiaaxx2#

你不会得到一个 InterruptedException 如果你不打断线程。
你可以试试,例如:

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

    Thread.sleep(1000);

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

ideone演示
输出:

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

相关问题