Java 不可能中断线程,如果它实际上正在计算?

Java 不可能中断线程,如果它实际上正在计算?,java,multithreading,concurrency,Java,Multithreading,Concurrency,根据这个代码 public class SimpleTest { @Test public void testCompletableFuture() throws Exception { Thread thread = new Thread(SimpleTest::longOperation); thread.start(); bearSleep(1); thread.interrupt(); bearSleep(5); } pu

根据这个代码

public class SimpleTest {

  @Test
  public void testCompletableFuture() throws Exception {
    Thread thread = new Thread(SimpleTest::longOperation);
    thread.start();

    bearSleep(1);

    thread.interrupt();

    bearSleep(5);
  }

  public static void longOperation(){
    System.out.println("started");
    try {

      boolean b = true;
      while (true) {
        b = !b;
      }

    }catch (Exception e){
      System.out.println("exception happened hurray!");
    }
    System.out.println("completed");
  }

  private static void bearSleep(long seconds){
    try {
      TimeUnit.SECONDS.sleep(seconds);
    } catch (InterruptedException e) {}
  }
}
想象一下,您拥有的不是这个
while(true)
而是不会抛出中断执行的东西(例如,一个实际计算某个东西的递归函数)

你怎么杀死这东西?为什么它没有死

注意,如果我不在那里输入
异常
并使用
InterruptedException
它甚至不会编译,说
“InterruptedException将永远不会被抛出”
,我不明白为什么。也许我想手动中断…

或多或少是用一个标志实现的。如果线程在某些操作上被阻塞,例如:IO或同步原语(请参阅Javadoc),则该线程将被解除阻塞,并在该线程中抛出一个
中断异常。否则,将设置一个简单的状态标志,指示线程已中断

您的代码需要使用或检查该状态(或处理
InterruptedException


请注意,使用
static
方法检查状态会清除状态。

我假设您指的是这段代码:

try {
    boolean b = true;
    while (true) {
        b = !b;
    }
} catch(Exception e) {
    System.out.println("exception happened hurray!");
}
您无法捕获
中断异常
的原因是该块中没有任何东西可以引发
中断异常
interrupt()
本身不会将线程从循环中断开,相反,它本质上会向线程发送一个信号,告诉它停止正在做的事情并做其他事情。如果希望
interrupt()
中断循环,请尝试以下操作:

boolean b = true;
while (true) {
    b = !b;
    // Check if we got interrupted.
    if(Thread.interrupted()) {
        break; // Break out of the loop.
    }
}

现在,线程将检查它是否被中断,并在中断后中断循环。不需要
try catch

@Vach
InterruptedException
是选中的异常。编译器知道何时可以抛出,何时不能抛出。在您的代码中,没有任何东西可以抛出它,因此您无法捕获它。@是的,请在执行过程中的适当点检查标志并采取适当的操作。谢谢,我知道并发是什么,但显然我还有很长的路要走:D@Vach一些关于如何处理中断的官方文档。请记住,在中断状态下,线程的状态是通过此方法清除的。这是正确的。如果要保留
interrupted
标志的状态,则应使用实例方法。