在使用wait()的时候,一定要放到synchronized块中,或者把方法定义为synchronized,不然会出现错误提示 current thread not owner。
synchronized块的执行效率比synchronized方法快很多,所以除非有特殊理由,一般情况下优先使用synchronized块。
同样,在其他线程中调用wait()线程的notify()或者是notifyAll()时,也要注意一定要使用synchronized,不然将无法找到线程。示例如下
class Exercise08A extends Thread {
public Exercise08A() {
start();
}
public void run() {
try {
System.out.println("waiting start");
synchronized (this) {
wait();
}
System.out.println("waiting end");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Exercise08B extends Thread {
Exercise08A ea;
public Exercise08B(Exercise08A ea) {
this.ea = ea;
start();
}
public void run() {
try {
System.out.println(" before notifyAll() ");
synchronized (ea) {
ea.notify();
}
System.out.println(" after notifyAll()");
} catch (Exception e) {
e.printStackTrace();
}
}
}