public class Test{
public static Integer i=0;
public static void main(String[] args) {
Object o1=new Object();
ReentrantLock lock=new ReentrantLock();
Thread t1=new Thread(new Runnable() {
@Override
public void run() {
lock.lock();
i++;
try {
this.wait(2000l);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(i);
lock.unlock();
}
});
Thread t2=new Thread(new Runnable() {
@Override
public void run() {
lock.lock();
i++;
System.out.println(i);
lock.unlock();
}
});
t1.start();
try {
Thread.sleep(10l);
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();
}
}
报错如下
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at com.suning.ctmodp.Controller.Test$1.run(Test.java:19)
at java.lang.Thread.run(Thread.java:748)
调用wait方法报错了,我觉得调用wait得时候t1是拿到自己得对象所得不知道为啥报这个,其实我一开始写的是lock.wait(),我就想看下wait是不是释放锁了,之前用sleep结果正确没有释放锁,难道lock之后不能调用wait方法吗