我写了一个程序来演示java的Lock.Condition用于多线程目的。我收到 IllegalMonitorStateException。
它抛出一个异常,以下是输出。
我在根据条件调用通知之前获取锁定。但仍然出现以下错误。有人可以帮忙吗。我用谷歌搜索了很多但找不到解决方案。
Count : 0
lock java.util.concurrent.locks.ReentrantLock@4ce4d37e[Locked by thread Thread-0]
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException: current thread is not owner
at java.base/java.lang.Object.notify(Native Method)
at test.OddEvenPrinter.printEven(Test.java:51)
at test.Test.lambda$main$1(Test.java:22)
at java.base/java.lang.Thread.run(Thread.java:1589)
Count : 1
lock java.util.concurrent.locks.ReentrantLock@4ce4d37e[Locked by thread Thread-1]
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException: current thread is not owner
at java.base/java.lang.Object.notify(Native Method)
at test.OddEvenPrinter.printOdd(Test.java:67)
at test.Test.lambda$main$0(Test.java:14)
at java.base/java.lang.Thread.run(Thread.java:1589)
它的代码如下:
package test;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Test {
public static void main(String[] args) {
final OddEvenPrinter oddEvenPrinter = new OddEvenPrinter();
Runnable oddRunnable = () -> {
try {
while (true)
oddEvenPrinter.printOdd();
} catch (InterruptedException e) {
e.printStackTrace();
}
};
Runnable evenRunnable = () -> {
try {
while (true)
oddEvenPrinter.printEven();
} catch (InterruptedException e) {
e.printStackTrace();
}
};
new Thread(evenRunnable).start();
new Thread(oddRunnable).start();
}
}
class OddEvenPrinter {
private final Lock lock = new ReentrantLock();
private final Condition oddPrint = lock.newCondition();
private final Condition evenPrint = lock.newCondition();
private int count;
public void printEven() throws InterruptedException {
lock.lock();
try {
Thread.sleep(3000);
while (count % 2 == 1) {
evenPrint.await();
}
System.out.println("Count : " + count++);
System.out.println("lock " + lock);
oddPrint.notify();
} finally {
lock.unlock();
}
}
public void printOdd() throws InterruptedException {
lock.lock();
try {
Thread.sleep(2000);
while (count % 2 == 0) {
oddPrint.await();
}
System.out.println("Count : " + count++);
System.out.println("lock " + lock);
evenPrint.notify();
} finally {
lock.unlock();
}
}
}
使用时
java.util.concurrent.locks.Condition
我们应该使用signal
orsignalAll
方法。例子:
和
notify
是notifyAll
与内在锁相关的方法(带有关键字synchronized
),例如:当我使用锁定条件时,我使用了通知而不是使用信号方法。
我粘贴更正后的代码以供将来参考。