Search code examples
javamultithreadingjava-threads

How to use wait() and notifyAll() to run thread one by one?


I write a House class, it has four synchronized method. I write four threads, and want they run one by one. but just first and second have run, the other havn't ?

public class House {

    private boolean hasFoundation = false;
    private boolean hasFrame = false;
    private boolean hasWall = false;
    private boolean hasRoof = false;

    public synchronized void buildFoundation() {
        hasFoundation = true;
        System.out.println("foundation Ok");
        notifyAll();
    }

    public synchronized void buildFrame() throws InterruptedException {
        if (!hasFoundation) {
            wait();
        } else {
            hasFrame = true;
            System.out.println("frame ok");
            notifyAll();
        }
    }

    public synchronized void buildWall() throws InterruptedException {
        if (!hasFrame) {
            wait();
        } else {
            hasWall = true;
            System.out.println("wall ok");
            notifyAll();
        }
    }

    public synchronized void buildRoof() throws InterruptedException {
        if (!hasWall) {
            wait();
        } else {
            hasRoof = true;
            System.out.println("roof ok");
            notifyAll();
        }
    }
}

public class BuildAHouse {

    public static void main(String[] args) {
        House house = new House();

        ExecutorService exec = Executors.newCachedThreadPool();

        exec.execute(new FoundationTeam(house));
        exec.execute(new WallTeam(house));
        exec.execute(new RoofTeam(house));

        exec.execute(new FrameTeam(house));

        exec.shutdown();
    }
}

when run the main(),the result just: foundation ok frame ok

the other two thread havn't run! why?

the ...Team class like this:

public class FoundationTeam implements Runnable {

    private House house;

    public FoundationTeam(House house) {
        this.house = house;
    }

    @Override
    public void run() {
        house.buildFoundation();
    }

}

this is just a demo, I want know how to use wait() and notifyAll().

Please just solve this problem ok? Its' just a part of all what i want do. Please just tell me why it's doesn't work, and how to solve?

when call wait(), this object won't be release? and other threads can't call the other synchronized methods?


Solution

  • If your method does wait(), it isn't going to run anything in the else block

    Note: wait() can wake spuriously, a while loop is recommended.