classZeroEvenOdd{ privateint n; Semaphore zero = new Semaphore(1); Semaphore even = new Semaphore(0); Semaphore odd = new Semaphore(0); publicZeroEvenOdd(int n){ this.n = n; }
// printNumber.accept(x) outputs "x", where x is an integer. publicvoidzero(IntConsumer printNumber)throws InterruptedException { for (int i = 1; i<=n; i++) { zero.acquire(); printNumber.accept(0); if (i % 2 == 0) { even.release(); } else { odd.release(); } } }
publicvoideven(IntConsumer printNumber)throws InterruptedException { for (int i = 2; i<=n; i=i+2) { even.acquire(); printNumber.accept(i); zero.release(); } }
publicvoidodd(IntConsumer printNumber)throws InterruptedException { for (int i = 1; i<=n; i=i+2) { odd.acquire(); printNumber.accept(i); zero.release(); } } }