Java监视器:如何知道等待(长时间超时)是否因超时或Notify()而结束? [英] Java Monitors: How to know if wait(long timeout) ended by timeout or by Notify()?

查看:150
本文介绍了Java监视器:如何知道等待(长时间超时)是否因超时或Notify()而结束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,这是一个近乎重复的:
如何区分等待(长时间超时)退出通知或超时?

First, this is a near duplicate of: How to differentiate when wait(long timeout) exit for notify or timeout?

但这是一个新的后续问题。

But it is a new follow-on question.

有这个等待声明:

public final native void wait(long timeout) throws InterruptedException;

它可能会被InterruptedException或超时退出,或者因为另一个线程中调用了Notify / NotifyAll方法,异常很容易捕获但是...

It could exit by InterruptedException, or by timeout, or because Notify/NotifyAll method was called in another thread, Exception is easy to catch but...

我的代码绝对需要知道退出是来自超时还是通知。 (将来,这段代码需要重新设计,但现在无法完成。所以我需要知道退出等待的原因。)

My code absolutely needs to know if the exit was from timeout or notify. (In the future, this code needs to be redesigned, but that cannot be done now. So I need to know the reason for the exit from wait.)

具体来说,有人可以给出一个示例使用ThreadLocal布尔值,该布尔值仅在notify()上设置为true,并且所有这些都在现有循环中,如下所示? (这或多或少是另一个线程中接受的答案,但没有给出具体的代码示例。我不熟悉Java,所以我需要一个特定的代码示例 - 理想情况下在现有代码的上下文中。)

Specifically, can someone give an example of using a ThreadLocal Boolean that is set to true only on notify() and where all this is inside an existing loop as shown below? (This was more or less the accepted answer in the other thread, but no specific code example was given. I'm not all that familiar with Java, so I need a specific code example -- ideally in the context of the existing code below.)

public synchronized int getLastSequenceNumber() {
    while (empty) {
        try {
            wait(waitTimeValue);
        } catch (InterruptedException e) {}
    }
    empty = true;
    return reportedSequenceNumber;
}
public synchronized void reconcileLastSequenceNumber(int sequenceNumber) {
    empty = false;
    this.reportedSequenceNumber = sequenceNumber;
    notifyAll();
}

布尔空用于特定问题之外的目的我是问这里我相信我需要添加另一个布尔值来满足原始问题的建议答案。如何将提议的解决方案集成到上面的现有代码片段中?谢谢。

the Boolean "empty" serves a purpose outside of the specific question I'm asking here. I believe I will need to add another Boolean to fulfill the suggested answer from the original question. How would I integrate that proposed solution into the existing code snippet above? Thanks.

推荐答案

使用 条件 (及其 等待 方法而不是内置监视器,因为等待返回 boolean 表示等待是否超时的值。

You might be better off using a Condition (and its await method) rather than built-in monitors, because await returns a boolean value indicating whether the wait timed out.

即便如此,你必须小心虚假唤醒(这与通话无法区分) 信号 。)

And even then, you must beware of spurious wakeup (which is indistinguishable from a call to signal.)

这篇关于Java监视器:如何知道等待(长时间超时)是否因超时或Notify()而结束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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