java监视器不好使_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 updateQueue = new LinkedBlockingQueue();

...

// 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,multithreading,synchronization

来源: https://codeday.me/bug/20190825/1720515.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值