gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:48:38 24 4
gpt4 key购买 nike

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

示例场景-

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.* 类,这些类允许您查看排队的成员,但不能从 synchronized (lock) 对象监视器的类型。

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 更新怎么样,这样收集器就可以检查队列并查看它是否非空。更新程序线程只会将 Update 信息添加到 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并发 - 监视器是否被阻止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17859474/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com