如何处理BlockingQueue的InterruptedException?

How to handle InterruptedException of BlockingQueue?

我有一个与此类似的代码,它位于 Runnablerun() 方法中,并且启动了 Runnable 的多个实例,

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

其中contractNums是一个被多个线程共享的BlockingQueue<String>。有单独的 Runnables 将元素放入此队列。

我不确定捕获 InterruptedException 后的下一步,我应该通过重新抛出一个 RuntimeException 来终止这个线程(所以我的 while 循环终止)还是尝试下一步再次来自 contractNum queue 的元素并忽略 InterruptedException?

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

求推荐。

视情况而定。是否有故意中断线程的地方,例如告诉它完成(例如在关闭期间)?如果不是,您只需要处理可能会唤醒线程的虚假中断。如果您不希望处理受到影响,请忽略它们。它们绝对不是 fatal 异常,您不需要记录它们(尤其是作为错误)。

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 章。

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