成功解决Exception in thread "main" java.lang.IllegalMonitorStateException
解决方法:
如果在非同步控制方法里调用java.util.concurrent.locks.Condition中的await()和signalAll()或者Object中的wait(),notify()和notifyAll()方法,程序能通过编译,但运行的时候,将得IllegalMonitorStateException异常。
以下代码就会报这个错误:
static volatile private ReentrantLock lock = new ReentrantLock();
static volatile private Condition condition =lock.newCondition();
static volatile private Boolean isWait=false;
private static void test() throws InterruptedException {
condition.await();
}
修改代码,添加锁即可,修改如下(添加synchronized 关键字也可以):
static volatile private ReentrantLock lock = new ReentrantLock();
static volatile private Condition condition =lock.newCondition();
static volatile private Boolean isWait=false;
private static void test() throws InterruptedException {
lock.lock();//只有一个线程可以执行下面的代码
condition.await();
lock.unlock();
}