如何安全地中断具有关键原子逻辑的线程? [英] How to safely interrupt a thread with critial atomic logic?

查看:48
本文介绍了如何安全地中断具有关键原子逻辑的线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个线程在循环中执行两件事:等待来自 BlockingQueue 的对象,然后处理它们.处理逻辑具有在 JVM 之外可观察到的效果,并且必须以原子方式完成.

I have a thread that does two stuff in a loop: wait for objects from a BlockingQueue and then process them. The processing logic has effects that is observable outside the JVM and must be done atomically.

目前这个线程由一个 volatile 布尔变量控制,如 https://stackoverflow.com/a/10961760/499922.但是,这意味着如果队列中没有更多消息供线程使用,线程将不会停止.'Thread.interrupt()` 不能用来解决这个问题,因为它可以中途中断原子操作.

Currently this thread is controlled by a volatile boolean variable like discussed in https://stackoverflow.com/a/10961760/499922. However, this means the thread will not stop if there are no more messages on the queue for it to consume. 'Thread.interrupt()` cannot be used to resolve this because it can interrupt the atomic operation half way.

有没有办法只中断队列上的 take() 方法而不中断任何其他操作?

Is there any way to just interrupt the take() method on the queue but not any other operation?

推荐答案

我发现在这种情况下最好的方法是使用毒丸"——您将一个对象放在队列中,该对象仅用于此目的切换某个动作.

I've found the best way in instances like this is to use the "Poison Pill" - you place an object on your queue which exists solely for the purpose of toggling a certain action.

它在实践中的 Java 并发中得到了广泛的介绍(​​我的副本中的第 155 页,第 7.2.3 页).请参阅此处,了解该部分的编程示例.

It's covered extensively in Java concurrency in practice (page 155, 7.2.3 in my copy). See here for the programmatic example from that section.

这篇关于如何安全地中断具有关键原子逻辑的线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆