gpt4 book ai didi

java - 同步调用锁定条件的 signalAll() 时出现 IllegalMonitorStateException

转载 作者:行者123 更新时间:2023-11-30 06:59:27 25 4
gpt4 key购买 nike

我有:

static public final ReentrantLock lock  = new ReentrantLock();
static public Condition my_condition = lock.newCondition();

myClass_1myClass_2 类中,我调用:

synchronized (myClass_1.my_condition){
myClass_1.my_condition.signalAll();
}

这给我 java.lang.IllegalMonitorStateException。我已经通过 signall() 调用进行了同步。可能是什么原因造成的?

最佳答案

这是因为在发送信号之前您没有获得 ReentrantLock 的锁。

阅读以下来自 ReentrantLock#newCondition 的重要声明

If this lock is not held when any of the Condition waiting or signalling methods are called, then an IllegalMonitorStateException is thrown.

此外,请阅读以下来自 Condition 的内容.现在,就像如果线程未获取锁则无法调用 wait() 一样,如果未获取锁则等待或发出信号。

Where a Lock replaces the use of synchronized methods and statements, a Condition replaces the use of the Object monitor methods.


底线:在等待或发出条件信号之前获取锁。

lock.lock();  //Get the lock
while(/* whatever is your condition in myClass_1 and myClass_2 */){ //Or negative condition you want, but some code logic condition...
my_condition.await();
}
my_condition_2.signal(); //If you want to notify one thread. Like in case of Java's blocking queue, if you want to notify one thread to put or take.
my_condition_2.signalAll(); //If you want to notify all threads.

关于java - 同步调用锁定条件的 signalAll() 时出现 IllegalMonitorStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31561492/

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