我有點難住。下面幾乎是從A simple scenario using wait() and notify() in java複製和粘貼。Java方法NotifyAll()不起作用?
據我的理解,這個Java程序應該在屏幕上打印yumyum..
,但事實並非如此。我在Eclipse中爲Mac OS X.任何想法我做錯了什麼?
public class Main {
public static void main(String[] args) {
MyHouse house = new MyHouse();
house.eatPizza();
house.pizzaGuy();
}
}
class MyHouse extends Thread {
private boolean pizzaArrived = false;
public void eatPizza() {
synchronized (this) {
while (!pizzaArrived) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
System.out.println("yumyum..");
}
public void pizzaGuy() {
synchronized (this) {
this.pizzaArrived = true;
notifyAll();
}
}
}
這是完美的匿名。謝謝! –
正確,不要使用'synchronized(this)',這會鎖定主對象,並且會阻塞主線程。嘗試將鎖定在虛擬對象上,我會工作得很好。 – Akash5288