using System.Threading; publicclassZeroEvenOdd { privateint n; public Semaphore semaphore = new Semaphore(1, 1);//奇数偶数打印完解锁 public Semaphore semaphore2 = new Semaphore(0, 1);//0打印完解锁打印奇数 public Semaphore semaphore3 = new Semaphore(0, 1);//0打印完解锁打印偶数
publicZeroEvenOdd(int n) { this.n = n; }
// printNumber(x) outputs "x", where x is an integer. publicvoidZero(Action<int> printNumber) { for(int i=0;i<n;i++) { semaphore.WaitOne(); printNumber(0); if(i%2 == 0) { semaphore2.Release(); } else { semaphore3.Release(); }