Java并发 – 监视器是否被阻止?

有没有办法从一个线程(比如一个锁定监视器对象的线程)判断另一个线程是否在同一个监视器上被阻塞/等待?

示例场景 –

a “collector” thread reads data from a shared object, while the
“updater” thread might be blocked and waiting for the collection to
end. I would like the collector to know that when he finishes
collecting, a possible data update is pending which yield the
collected data might already be invalid.

在我的情况下,收集可能是一个耗时的操作,并且在下一阶段,“收集器”线程分析数据一段时间,这在数据无效的许多情况下可能是冗余操作.

解决方法:

Is there a way to tell from one thread (say the one which locks a monitor object) if another thread is block/waiting on same monitor?

不,不是来自对象本身.正如@Evgeniy所提到的,您可以使用其他java.util.concurrent.locks.*类,它们允许您查看排队成员,但不能查看同步(锁定)类型的对象监视器.

I would like the collector to know that when he finishes collecting, a possible data update is pending which yield the collected data might already be invalid.

如何使用BlockingQueue更新,以便收集器可以检查队列并查看它是否为非空.更新程序线程只是将更新信息添加到BlockingQueue,收集器将使更新出列并进行调整.然后它可以检查队列的长度并决定是否需要进入分析模式.

private BlockingQueue<Update> updateQueue = new LinkedBlockingQueue<Update>();
...
// called by the updater thread(s)
public void updateData(Update update) {
    updateQueue.put(update);
}
// called by the collector
public void collect() {
    while (!Thread.currentThread().isInterrupted()) {
        Update update = updateQueue.take();
        updateValues(update);
        if (updateQueue.isEmpty()) {
           analyzeData();
        }
    }
}

无论您如何操作,您都需要使用其他机制来考虑新数据更新,而不是检查所有线程的阻塞状态.

上一篇:java – 每次触发侦听器时,我的侦听器实现是否正在创建一个新数组?


下一篇:c – 这些Boost :: Interprocess组件是否需要同步?