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