Java 线程 : Shutdown flag vs Catching Exception

标签 java multithreading request-cancelling

在线程中处理取消时,经常会看到这样的代码

while (!shutdown) {
  .. do something, if a blocking call, then it will throw the interrupted exception
  try { .. some more ... } 
  catch (InterruptedException e) { 
    shutdown = true; 
  }
}

我想知道的是,是不是这样,或者为什么这样,比这样做更好

try {
  while (true) {
    .. do something, if a blocking call, then it will throw the interrupted exception
    if (Thread.interrupted()) throw new InterruptedException();
  }
} catch (InterruptedException e) {
  .. clean up, let thread end
}

我的看法是,在后一种情况下,您根本不需要理会 shutdown var。

最佳答案

在第一个版本中,您可以与调用代码共享关闭标志(或类似的关闭机制),允许它仅通过设置标志就可以尝试完全正常关闭,而不会中断线程——可能回退到中断如果正常关机失败。

我不建议使用线程中断作为您唯一的关闭机制。

(同样,当然,要小心处理共享标志的方式。您需要使其成为线程安全的;在简单情况下,volatile 变量可能就足够了。)

关于Java 线程 : Shutdown flag vs Catching Exception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5513092/

相关文章:

java - 如何将 HTML 表单数据发送到 Java http 服务器

c++ - FAST DMA 受益于在 C++ 中使用线程的 FPGA

java - 难以找到最高平均值

java - 继承和 LSP

java方法同步和读/写互斥

c# - 如何取消深度嵌套的进程

ajax - 如何正确取消永远不会完成的未完成的 Ajax 请求?

java - Stackoverflow 是由简单的代码引起的

c++ - Libuv:保护事件循环免受并发访问