|
|
@@ -0,0 +1,76 @@
|
|
|
+package leetcode.p1114;
|
|
|
+
|
|
|
+/**
|
|
|
+ * @ProjectName: LeetCode
|
|
|
+ * @FileName: Foo
|
|
|
+ * @Author: 杨逸
|
|
|
+ * @Data:2026/3/25 19:24
|
|
|
+ * @Description: https://leetcode.cn/problems/print-in-order/description/
|
|
|
+ * 1114. 按序打印
|
|
|
+ */
|
|
|
+public class Foo {
|
|
|
+ /**
|
|
|
+ * 加锁和添加执行屏障解法
|
|
|
+ */
|
|
|
+ private boolean firstFinished = false;
|
|
|
+ private boolean secondFinished = false;
|
|
|
+ public Foo() {
|
|
|
+ }
|
|
|
+
|
|
|
+ public void first(Runnable printFirst) throws InterruptedException {
|
|
|
+ synchronized (this){
|
|
|
+ printFirst.run();
|
|
|
+ firstFinished = true;
|
|
|
+ notifyAll();
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ public void second(Runnable printSecond) throws InterruptedException {
|
|
|
+ synchronized (this){
|
|
|
+ while (!firstFinished){wait();}
|
|
|
+ printSecond.run();
|
|
|
+ secondFinished = true;
|
|
|
+ notifyAll();
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ public void third(Runnable printThird) throws InterruptedException {
|
|
|
+ synchronized (this){
|
|
|
+ while (!secondFinished)wait();
|
|
|
+ printThird.run();
|
|
|
+ notifyAll();
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+/**
|
|
|
+ * 使用volatile关键字实现线程可见性
|
|
|
+ * @author 杨逸
|
|
|
+ * @date 2026/03/25 19:35:21
|
|
|
+ */
|
|
|
+class VolatileSolution{
|
|
|
+ private volatile int flag;
|
|
|
+ public VolatileSolution() {
|
|
|
+ flag = 1;
|
|
|
+ }
|
|
|
+
|
|
|
+ public void first(Runnable printFirst) throws InterruptedException {
|
|
|
+ while (flag!=1){}
|
|
|
+ // printFirst.run() outputs "first". Do not change or remove this line.
|
|
|
+ printFirst.run();
|
|
|
+ flag = 2;
|
|
|
+ }
|
|
|
+
|
|
|
+ public void second(Runnable printSecond) throws InterruptedException {
|
|
|
+ while (flag!=2){}
|
|
|
+ // printSecond.run() outputs "second". Do not change or remove this line.
|
|
|
+ printSecond.run();
|
|
|
+ flag = 3;
|
|
|
+ }
|
|
|
+
|
|
|
+ public void third(Runnable printThird) throws InterruptedException {
|
|
|
+ while (flag!=3){}
|
|
|
+ // printThird.run() outputs "third". Do not change or remove this line.
|
|
|
+ printThird.run();
|
|
|
+ }
|
|
|
+}
|