java - 如果它实际计算就不可能中断线程?

标签 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);
  }

  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),你有一些不会引发中断执行的东西(例如,一个实际计算某些东西的递归函数)。

你怎么杀死这个东西?为什么它不死?

请注意,如果我不在那里放置 Exception 类型并使用 InterruptedException 它甚至不会编译,说 “永远不会抛出中断的异常” 我不明白为什么。也许我想手动打断它...

最佳答案

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

try {
    boolean b = true;
    while (true) {
        b = !b;
    }
} catch(Exception e) {
    System.out.println("exception happened hurray!");
}

您无法在此处捕获 InterruptedException 的原因是因为该 block 内没有任何内容可以抛出 InterruptedExceptioninterrupt() 本身不会让线程跳出循环,相反,它本质上是向线程发送一个信号,告诉它停止正在做的事情并做其他事情。如果你想要 interrupt() 打破循环,试试这个:

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

现在线程将检查它是否被中断,一旦被中断就跳出循环。无需 try-catch

关于java - 如果它实际计算就不可能中断线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29015235/

相关文章:

java - 日期差异包括时区偏移,怎么了?

C++ OpenMP : Split for loop in even chunks static and join data at the end

Python Semaphore 似乎在 Google Colab 中不起作用

Python:为什么线程函数比非线程函数慢

java - Mockito:在 X 调用上返回 NULL

java - hibernate 错误: HHH000091

java - 信号量和条件的区别(ReentrantLock)

c++ - 从 std::scoped_lock 抛出的异常

multithreading - 使用 Stanford CoreNLP (3.5.2) 进行并发处理

java - Jsoup 1.7.1 错误?