java - 如何处理BlockingQueue的InterruptedException?

标签 java multithreading concurrency blockingqueue

<分区>

我在 run() 中有一个与此类似的代码Runnable 的方法和那个 Runnable 的多个实例启动,

do{
        try{
            String contractNum=contractNums.take();
           }catch(InterruptedException e){
            logger.error(e.getMessage(), e);
        }
  }while(!("*".equals(contractNum)));

在哪里contractNumsBlockingQueue<String>由多个线程共享。有单独的Runnables将元素放入此队列。

我不确定抓到 InterruptedException 后的下一步,我应该通过重新抛出 RuntimeException 来终止这个线程吗? (所以我的 while 循环终止)或尝试从 contractNum queue 中获取下一个元素再次忽略InterruptedException

我不确定 InterruptedException被视为线程终止或将其保留在 while 循环中的致命条件。

请推荐。

最佳答案

7.1.2 中断政策

Just as tasks should have a cancellation policy, threads should have an interruption policy. An interruption policy determines how a thread interprets an interruption request—what it does (if anything) when one is detected, what units of work are considered atomic with respect to interruption, and how quickly it reacts to interruption. The most sensible interruption policy is some form of thread-level or service- level cancellation: exit as quickly as practical, cleaning up if necessary, and pos- sibly notifying some owning entity that the thread is exiting. It is possible to establish other interruption policies, such as pausing or resuming a service, but threads or thread pools with nonstandard interruption policies may need to be restricted to tasks that have been written with an awareness of the policy.

7.1.3 响应中断

As mentioned befor, when you call an interruptible blocking method such as Thread.sleep or BlockingQueue.put , there are two practical strategies for handling InterruptedException :

• Propagate the exception (possibly after some task-specific cleanup), making your method an interruptible blocking method, too; or

• Restore the interruption status so that code higher up on the call stack can deal with it.

Java Concurrency in Practice第 7 章。

特别是在您的代码中,您需要确保如果线程被中断,您的应用程序逻辑不会被破坏。 而且捕获你的中断异常确实更好。如何使用它取决于您,只需尝试确保您不会破坏应用程序逻辑即可。

关于java - 如何处理BlockingQueue的InterruptedException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36473046/

相关文章:

php - pfsockopen 线程安全?

java - 对于受 OAuth 2 保护的 Spring Boot REST API,如何在将请求转发到方法之前拦截访问 token ?

python - 如何在 python 中创建一个线程安全的全局计数器

c# - 为什么我尝试在 C# 中实现基本自旋锁时会得到这个结果?

c# - 每个托管线程是否都有自己对应的 native 线程?

java - 如何实现用于流式传输斐波那契数的 Spliterator?

java - 手动添加@PropertySource : Configuring Environment before context is refreshed

java - 黑莓浏览器问题

java - 如何在没有嵌套订阅的情况下组合/链接包含不同数据类型的多个 Mono/Flux

python - 我应该担心在多线程 python 脚本中并发访问字典吗?