- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我很困惑,无法理解为什么不应该吞下 InterruptedException。
IBM 的文章说
当阻塞方法检测到中断并抛出 InterruptedException 时,它会清除中断状态。如果您捕捉到 InterruptedException 但无法重新抛出它,您应该保留中断发生的证据以便调用堆栈上层的代码可以了解中断并在需要时做出响应
public class TaskRunner implements Runnable {
private BlockingQueue<Task> queue;
public TaskRunner(BlockingQueue<Task> queue) {
this.queue = queue;
}
public void run() {
try {
while (true) {
Task task = queue.take(10, TimeUnit.SECONDS);
task.execute();
}
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();//preserve the message
return;//Stop doing whatever I am doing and terminate
}
}
}
此外,Java 并发实践在第 7.1.3 章:响应中断中对此进行了更详细的讨论。它的规则是:
只有实现线程中断策略的代码才能吞下中断请求。通用任务和库代码永远不应吞噬中断请求。
1.谁能解释一下高层调用堆栈中的代码如何利用 Thread.currentThread().interrupt(); 设置的状态?线程终止时在 catch block 中?
另外请解释一下上面的规则?
最佳答案
看看这个例子,我们假设它在线程/线程池上下文中运行。
public void run() {
// Honor interrupts so that you can stop/kill the task
while (!Thread.currentThread().interrupted()) {
this.doSomeChunkOfWork();
}
}
上面的代码是一个很好的例子,说明了如何编写一个可以被中断并分块处理数据的任务(想想从某些源读取数据并分部分处理数据)。现在让我们假设 doSomeChunkOfWork
被中断并且您捕获了一个异常。除非你再次设置标志或保持标志的中断状态,否则 run
方法将无法知道当方法调用返回时调用堆栈深处的处理被中断,这搞砸了我们的好逻辑。
这就是为什么您总是将状态设置回去,以便调用堆栈中的方法知道线程是否真的被中断了。我想为此做一个类比是“不要扫地毯下的污垢”。 :)
关于java - 为什么我们不应该吞下 InterruptedException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18682333/
我需要浏览一个文件,然后将捆绑包与另一个文件连接起来。我尝试了下面的 gulp 代码,但它无法正常工作。 当我在 mymodule.js 中进行更改并运行 gulp 时,这些更改会出现在包文件中,但不
尝试创建 Flux 存储。当我运行 gulp 并检查我的 index.html 时,出现错误“Uncaught TypeError:监听器必须是函数” var AppDispatcher = requ
我在提醒自己“关键字”时偶然发现了这篇文章 http://effbot.org/zone/python-with-statement.htm 。我只是有一个小问题,可能是显而易见的问题。文章指出,这“
我正在使用 Oracle 11g(瘦驱动程序)和 Java 6 在 Windows 上的 Tomcat 7 中开发一个应用程序。我正在开发一个页面,让用户验证存储在 Oracle 数据库中的 SQL
除了向每个回调添加 try..catch block 之外,是否有任何方法可以处理从 jQuery 中的 AJAX 回调抛出的异常?在这种情况下不会调用错误函数。 $.ajax( { url:
我已经编写了代码(如下),以便能够将输入字段拖到另一个输入字段上,但似乎可拖动的燕子 input[text].onfocus . 这会导致问题,即所有可拖动的输入字段都被禁用(firefox)并且单击
在 jQuery 中,如果您在 ajax 回调方法中出错,您将收到正确的控制台错误消息和堆栈跟踪。 $.get("https://api.github.com/users/octocat/orgs",
我正在使用 Apache PdfBox 库,我注意到几乎所有东西都会抛出 IOException,考虑到大多数 IOException 实际上应该是非法状态异常,处理起来非常烦人,但似乎 apache
嘿,我是原型(prototype)的新手。问题是 dom:loaded 回调函数中的 javascript 错误不会在 firefox (webconsole/errorconsole/firebug
我有一个文本框,里面有这个: 问题是它吞下了 Tab 而不是跳转到下一个控件。如何捕获文本框的 Tab 键并仍然按 Tab 键顺序保留到下一个控件的 Tab 键?编辑:我也在使用 MVVM 并且 M
我正在尝试让 googletest 在我的 C++ 项目上运行,其中一部分涉及使用 EXPECT_THROW(statement, expected_exception);。我正在使用选择了“Appl
我不明白为什么原型(prototype)会抑制 dom:loaded 事件和 AJAX 处理程序中的错误消息。 给定以下 HTML 片段: Conforming XHTM
我是一名优秀的程序员,十分优秀!