This question already has answers here:
Why must wait() always be in synchronized block

(10个回答)


7年前关闭。




在我读的书中,它说:



不明白这到底意味着什么,为什么会发生种族状况?

编辑:嗯,我现在看到这可能是Why must wait() always be in synchronized block的重复问题
,但它接缝的答案集中在使条件检查和等待同步上。

来自shrini1000的反例:

最佳答案

在您复制有问题的文章之前,这一定是作者必须介绍的技术的全部内容。我不确定您正在阅读哪本书,但我会尽力回答这个问题。

我读过类似的书《 Thinking in Java》,该书谈到了相同的竞争条件。这表明可以使用等待通知来防止这种情况发生,以使代码不会错过通知信号。



T1:

synchronized(sharedMonitor) {
    <setup condition for T2>
    sharedMonitor.notify();
}

T2:
while(someCondition) {
    // Assume that T2 evaluates someCondition and finds
    // it true, now when program goes to next line thread
    // scheduler switches to T1 and executes notify again
    // after when control comes to T2 it blindly executes
    // wait(), but it has already missed notify so it will
    // always be waiting.

    .... some code ....

    synchronized(sharedMonitor) {
        sharedMonitor.wait();
    }
}

(T2的设置条件)是一项防止T2调用wait()的操作(如果尚未调用的话)。

解决方案是防止在someCondition变量上出现争用条件。这是T2的正确方法:
synchronized(sharedMonitor) {
    while(someCondition) {
        sharedMonitor.wait();
    }
}

10-07 16:19
查看更多