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

ShS*_*ShS 3 java multithreading locking synchronized

我有:

static public final ReentrantLock lock  = new ReentrantLock();
static public Condition my_condition    = lock.newCondition();
Run Code Online (Sandbox Code Playgroud)

myClass_1myClass_2I类电话:

synchronized (myClass_1.my_condition){
    myClass_1.my_condition.signalAll();
}
Run Code Online (Sandbox Code Playgroud)

这给了我java.lang.IllegalMonitorStateException. 我已经在signall()通话中同步了。是什么原因造成的?

hag*_*wal 6

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

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

如果在调用任何 Condition 等待或信号方法时持有此锁,则抛出 IllegalMonitorStateException。

另外,请阅读下面的Condition。现在,就像wait()如果线程没有获取锁就不能调用一样,如果没有获取锁,你就等待或发出信号条件。

Lock 代替了同步方法和语句的使用,而 Condition 代替了对象监视器方法的使用


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

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.
Run Code Online (Sandbox Code Playgroud)