|
@@ -0,0 +1,81 @@
|
|
|
|
|
+package leetcode.p1115;
|
|
|
|
|
+
|
|
|
|
|
+import java.util.concurrent.Semaphore;
|
|
|
|
|
+import java.util.concurrent.locks.Condition;
|
|
|
|
|
+import java.util.concurrent.locks.ReentrantLock;
|
|
|
|
|
+
|
|
|
|
|
+/**
|
|
|
|
|
+ * @ProjectName: LeetCode
|
|
|
|
|
+ * @FileName: FooBar
|
|
|
|
|
+ * @Author: 杨逸
|
|
|
|
|
+ * @Data:2026/3/25 21:11
|
|
|
|
|
+ * @Description: https://leetcode.cn/problems/print-foobar-alternately/
|
|
|
|
|
+ * 1115. 交替打印 FooBar
|
|
|
|
|
+ */
|
|
|
|
|
+public class FooBar {
|
|
|
|
|
+ private int n;
|
|
|
|
|
+ private volatile boolean fooFlag = true;
|
|
|
|
|
+ private final ReentrantLock lock;
|
|
|
|
|
+ private final Condition condition;
|
|
|
|
|
+ public FooBar(int n) {
|
|
|
|
|
+ this.n = n;
|
|
|
|
|
+ lock = new ReentrantLock();
|
|
|
|
|
+ condition = lock.newCondition();
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ public void foo(Runnable printFoo) throws InterruptedException {
|
|
|
|
|
+ for (int i = 0; i < n; i++) {
|
|
|
|
|
+ lock.lock();
|
|
|
|
|
+ try {
|
|
|
|
|
+ while (!fooFlag)condition.await();
|
|
|
|
|
+ printFoo.run();
|
|
|
|
|
+ fooFlag = !fooFlag;
|
|
|
|
|
+ condition.signalAll();
|
|
|
|
|
+ } finally {
|
|
|
|
|
+ lock.unlock();
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ public void bar(Runnable printBar) throws InterruptedException {
|
|
|
|
|
+ for (int i = 0; i < n; i++) {
|
|
|
|
|
+ lock.lock();
|
|
|
|
|
+ try {
|
|
|
|
|
+ while (fooFlag)condition.await();
|
|
|
|
|
+ printBar.run();
|
|
|
|
|
+ fooFlag = !fooFlag;
|
|
|
|
|
+ condition.signalAll();
|
|
|
|
|
+ } finally {
|
|
|
|
|
+ lock.unlock();
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+}
|
|
|
|
|
+class SemaphoreSolution{
|
|
|
|
|
+ private int n;
|
|
|
|
|
+ private final Semaphore semaphore1 = new Semaphore(1);
|
|
|
|
|
+ private final Semaphore semaphore2 = new Semaphore(0);
|
|
|
|
|
+ public SemaphoreSolution(int n) {
|
|
|
|
|
+ this.n = n;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ public void foo(Runnable printFoo) throws InterruptedException {
|
|
|
|
|
+
|
|
|
|
|
+ for (int i = 0; i < n; i++) {
|
|
|
|
|
+ semaphore1.acquire();
|
|
|
|
|
+ // printFoo.run() outputs "foo". Do not change or remove this line.
|
|
|
|
|
+ printFoo.run();
|
|
|
|
|
+ semaphore2.release();
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ public void bar(Runnable printBar) throws InterruptedException {
|
|
|
|
|
+
|
|
|
|
|
+ for (int i = 0; i < n; i++) {
|
|
|
|
|
+ semaphore2.acquire();
|
|
|
|
|
+ // printBar.run() outputs "bar". Do not change or remove this line.
|
|
|
|
|
+ printBar.run();
|
|
|
|
|
+ semaphore1.release();
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+}
|