也就是当前的线程不是此对象监视器的所有者。当前线程要锁定该对象之后,才能用锁定的对象执行这些方法,这里需要用到synchronized关键字,锁定哪个对象就用哪个对象来执行notify(), notifyAll(),wait(), wait(long), wait(long, int)操作,否则就会报IllegalMonitorStateException异常。
1.锁定方法的所属的实例对象
public synchronized void method(){
//然后就可以调用:this.notify()...
//或者直接调用notify()...
}
2.锁定方法所属的实例的class
public Class Test{
public static synchronized void method(){
//然后调用:Test.class.notify()...
}
}
3.锁定其他对象:
public Class Test{
public Object lock = new Object();
public static void method(){
synchronized (lock) {
//需要调用 lock.notify();
}
}
}
测试:
private Person person = new Person();
public void addProduct(){
synchronized (person){
try {
//wait();//IllegalMonitorStateException
//person.wait();//正常
Clerk.class.wait();//IllegalMonitorStateException
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
测试2:
public class Clerk {
//当前商品数量
private int product = 0;
private static Person person = new Person();
public static synchronized void addProduct(){
try {
//wait();//编译报错
// person.wait();//IllegalMonitorStateException
//Person.class.wait();//IllegalMonitorStateException
Clerk.class.wait();//正常
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}