程序如下publicclassWait$Notify$NotifyAll{publicstaticvoidmain(Stringargs[]){finalMyBasket2basket=newMyBasket2();newThread(){@Overridepublicvoidrun(){try{sleep(1500);}catc...
程序如下
public class Wait$Notify$NotifyAll {
public static void main(String args[]) {
final MyBasket2 basket = new MyBasket2();
new Thread() {
@Override
public void run() {
try {
sleep(1500);
} catch (InterruptedException ex) {
}
basket.set(100, 5);
}
}.start();
new Thread() {
@Override
public void run() {
try {
sleep(1000);
} catch (InterruptedException ex) {
}
System.out.println(basket.calc());
}
}.start();
}
}
class MyBasket2 extends MyBasket {
@Override
public synchronized void set(long price, int quantity) {
super.set(price, quantity);
notify();
}
@Override
public String calc() {
if (price == 0 && quantity == 0) {
try {
wait();
} catch (InterruptedException ex) {
}
}
return super.calc();
}
}
class MyBasket {
protected long price = 0;
protected int quantity = 0;
public void set(long price, int quantity) {
this.price = price;
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
this.quantity = quantity;
}
public String calc() {
long total = price * quantity;
return price + "*" + quantity + "=" + total;
}
}
按照预期,应该得到100*5=500。
但是虽然编译成功,却总是出现执行错误:
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:503)
at javaapp.thread.MyBasket2.calc(Wait$Notify$NotifyAll.java:42)
at javaapp.thread.Wait$Notify$NotifyAll$2.run(Wait$Notify$NotifyAll.java:24)
NetBeans显示wait()没用对地方,那么该怎么用呢,请各位指教。
展开