Search code examples
javaeclipsemultithreadingwait

Java method NotifyAll() isn't working?


I'm a little stumped. Below is pretty much a copy and paste from A simple scenario using wait() and notify() in java.

To my understanding, this Java program below should be printing yumyum.. to the screen but it isn't. I am in Eclipse for Mac OS X. Any ideas what I'm doing wrong ?

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();
        }
    }
}

Solution

  • Try this...

    public class Main {
    
        public static void main(String[] args) {
            MyHouse house = new MyHouse();
            house.start();
    //        house.eatPizza();
            // Halt main thread momentarily to delay Mr Pizza Guy
            try { Thread.sleep(3000); } catch(Exception e) {}
            house.pizzaGuy();
    
        }
    }
    
    class MyHouse extends Thread {
    
        private boolean pizzaArrived = false;
        private Object lock = new Object();
    
        @Override
        public void run() {
            eatPizza();
        }
    
        public void eatPizza() {
            synchronized (lock) {
                while (!pizzaArrived) {
                    try {
                        System.out.println("Waiting for Pizza guy");
                        lock.wait();
                    } catch (InterruptedException e) {
                    }
                }
                System.out.println("Pizza arrived!!!");
            }
            System.out.println("yumyum..");
        }
    
        public void pizzaGuy() {
            synchronized (lock) {
                this.pizzaArrived = true;
                lock.notifyAll();
            }
        }
    }