当线程处于被锁定的关键部分时,我需要以某种方式停止线程 1 秒ReentrantLock
。
我的代码是:
public class Lock implements Runnable {
private ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
try {
lock.lock();
System.out.println(Thread.currentThread().getName() + " is running !");
lock.wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
Lock lock = new Lock();
Thread thread = new Thread(lock);
thread.start();
}
}
当我调用lock.wait(1000)
run() 方法时,它会抛出IllegalMonitorStateException
.
如果我通过lock.lock()
方法获得监视器,为什么会出现此异常?
当我打电话super.wait(1000)
而不是lock.wait(1000)
.