WaitingRoom.java 1.15 KB
Newer Older
Michele Fiori's avatar
Michele Fiori committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
package veterinarian;

public class WaitingRoom {
    private int dogs = 0;
    private int cats = 0;

    public synchronized void EnterRoom(String animal, int id) throws InterruptedException {
        while(!checkConditions(animal)) {
            wait();
        }

        if(animal.equals("cat")) {
            cats += 1;
        }

        if(animal.equals("dog")) {
            dogs += 1;
        }
        System.out.println(animal + " " + id + " entered! Dogs: " + dogs + ", Cats: " + cats);
    }

    public synchronized void ExitRoom(String animal, int id) {
        if(animal.equals("cat")) {
            cats -= 1;
        }

        if(animal.equals("dog")) {
            dogs -= 1;
        }
        System.out.println(animal + " " + id + " exited! Dogs: " + dogs + ", Cats: " + cats);
        notifyAll();
    }

    private boolean checkConditions(String animal) {
        if(animal.equals("cat")) {
            return dogs <= 0 && cats <= 0;
        }

        else {
            if(cats > 0) {
                return false;
            } else {
                return dogs < 3;
            }
        }
    }
}