// in SharedN.java

public class SharedN {
    public int n;
    int cValueAvail = 0;	// cause IncrementN to run first

    public SharedN() {
	n = 0;			// initialize N to zero
    }

    // use synchronized and condition to control access to N
    public synchronized void IncrementN() {
	while (cValueAvail > 0) {
	    try {
		wait();   // wait for value to be consumed
	    } catch (InterruptedException e) {
		System.out.println("Wait interrupted");
	    }
	}
	n++;
	cValueAvail = 1;
	notifyAll();  // could also use notify() if only one is waiting
    }

    public synchronized int ReadN() {
	while (cValueAvail == 0) {
	    try {
		wait();   // wait for value to be produced
	    } catch (InterruptedException e) {
		System.out.println("Wait interrupted");
	    }
	}
	cValueAvail = 0;
	notifyAll();  // could also use notify() if only one is waiting
	return n;  // return value of n (will continue after notify)
    }

}

