|
@@ -0,0 +1,58 @@
|
|
|
|
|
+package leetcode.p1116;
|
|
|
|
|
+
|
|
|
|
|
+import java.util.concurrent.Semaphore;
|
|
|
|
|
+import java.util.function.IntConsumer;
|
|
|
|
|
+
|
|
|
|
|
+/**
|
|
|
|
|
+ * @ProjectName: LeetCode
|
|
|
|
|
+ * @FileName: ZeroEvenOdd
|
|
|
|
|
+ * @Author: 杨逸
|
|
|
|
|
+ * @Data:2026/3/25 21:33
|
|
|
|
|
+ * @Description: https://leetcode.cn/problems/print-zero-even-odd/
|
|
|
|
|
+ * 1116. 打印零与奇偶数
|
|
|
|
|
+ */
|
|
|
|
|
+public class ZeroEvenOdd {
|
|
|
|
|
+ private int n;
|
|
|
|
|
+ private volatile int val;
|
|
|
|
|
+ private final Semaphore zero;
|
|
|
|
|
+ private final Semaphore even;
|
|
|
|
|
+ private final Semaphore odd;
|
|
|
|
|
+
|
|
|
|
|
+ public ZeroEvenOdd(int n) {
|
|
|
|
|
+ this.n = n;
|
|
|
|
|
+ val = 0;
|
|
|
|
|
+ zero = new Semaphore(1);
|
|
|
|
|
+ even = new Semaphore(0);
|
|
|
|
|
+ odd = new Semaphore(0);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // printNumber.accept(x) outputs "x", where x is an integer.
|
|
|
|
|
+ public void zero(IntConsumer printNumber) throws InterruptedException {
|
|
|
|
|
+ for (int i = 0; i < n; i++) {
|
|
|
|
|
+ zero.acquire();
|
|
|
|
|
+ printNumber.accept(0);
|
|
|
|
|
+ val++;
|
|
|
|
|
+ if ((val%2) == 0) {
|
|
|
|
|
+ even.release();
|
|
|
|
|
+ } else {
|
|
|
|
|
+ odd.release();
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ public void even(IntConsumer printNumber) throws InterruptedException {
|
|
|
|
|
+ for (int i = 2; i <= n; i+=2) {
|
|
|
|
|
+ even.acquire();
|
|
|
|
|
+ printNumber.accept(val);
|
|
|
|
|
+ zero.release();
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ public void odd(IntConsumer printNumber) throws InterruptedException {
|
|
|
|
|
+ for (int i = 1; i <= n; i+=2){
|
|
|
|
|
+ odd.acquire();
|
|
|
|
|
+ printNumber.accept(val);
|
|
|
|
|
+ zero.release();
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+}
|