InterruptException 是否导致线程停止

Does an InterruptException cause the thread to stop

我以为如果抛出异常,当前正在执行的Thread就会弯腰。但是,当我进行 java 测试时遇到了一个问题:

Under which conditions will a currently executing thread stop?

  1. When an interrupted exception occurs.

  2. When a thread of higher priority is ready (becomes runnable).

  3. When the thread creates a new thread.

  4. When the stop() method is called.

A. 1 and 3

B. 2 and 4

C. 1 and 4

D. 2 and 3

正确答案是B,但是如果抛出异常会发生什么?我以为线程正在终止。

The right answer was B

不,不是。 None 的答案是正确的。

but what then happens if the exception is thrown? I thought the thread is terminating.

没有。线程从它调用的任何可以抛出它的方法中捕获 InterruptedException,例如 Thread.sleep()。如果它不调用这样的方法,则什么也不会发生。

当一个方法抛出 InterruptedException 时,它表明它是一个 阻塞方法 并且它将尝试解除阻塞并 return 尽早——如果你好好问

当您尝试通过在线程实例上调用 interrupt() 来中断线程时,它只会发送一个信号。这取决于响应该信号的实际线程。 Thread.sleep() 和 Object.wait() 之类的方法可以查找此信号并尝试停止其正在执行的操作,并尽早 return 和 通过抛出 InterruptedException 来指示它的早期 return。所以它通常是一些阻塞方法对其他线程发送的 interrupt() 请求的确认。

        Thread t = new Thread(() -> {
             try {
                 Thread.sleep(5000); // Thread.sleep() allows a cancellation mechanism
            } catch (Exception e) {
                System.out.println("interrupted by some one else from outside");
            }
         });

         t.start();
         try {
            t.interrupt();
            t.join(); // waiting for the thread to finish its execution
            System.out.println("back in main");
        } catch (InterruptedException e) {
            System.out.println("interrupted");
        }

输出:

interrupted by some one else from outside
back in main

但是如果你有这样的线程

       Thread t = new Thread(() -> {
             try {
                 for(int i=0;i<1_000_000;i++){
                     System.out.println(i);
                 }
            } catch (Exception e) {
                System.out.println("interrupted by some one else from outside");
            }
       });

在上面的线程上调用 interrupt() 不会做任何有用的事情,因为我们不是在寻找信号,所以线程将打印所有数字并加入主线程,就好像没有人要求它停止它正在做的事情一样做.

如果您想了解有关此 InterruptedException 的更多信息,我强烈推荐 this来自 IBM Developer Works 的 Brian Goetz 文章

一个线程 t 将在其他线程调用 t.stop() 时停止,但是 永远不要那样做!一个线程不应该强制另一个线程做任何事情。线程应该始终协作。任何调用 t.stop() 的程序很可能包含错误,如果不摆脱 stop() 调用就无法修复这些错误。

如果某个外部进程终止了 JVM,线程将终止(这是一种停止,对吧?)。

如果 JVM 关闭,守护线程 将终止,因为没有非守护线程保持活动状态。

线程可能会由于附加调试器的操作而停止或终止。

线程停止(并终止)的唯一其他原因是它的 run() 方法 完成 。方法可以通过返回正常完成,也可以异常终止(即抛出异常但未捕获 在方法调用中。)如果线程的 运行() 方法以任一方式完成,线程将终止。

InterruptedException 对线程的影响与任何其他异常没有任何不同。如果线程捕获到异常,那么线程会继续运行,但是如果线程中没有方法捕获,那么线程的运行()方法就会异常完成,并且线程将终止(停止)。