LeetCode 1114. Print in Order--Java解法--并发问题--使用 synchronized, wait, notifyAll保证并发的顺序

2020/01/11 共 1785 字，约 6 分钟

LeetCode题解专栏：LeetCode题解
LeetCode 所有题目总结：LeetCode 所有题目总结

Suppose we have a class:

``````public class Foo {
public void first() { print("first"); }
public void second() { print("second"); }
public void third() { print("third"); }
}
``````

The same instance of Foo will be passed to three different threads. Thread A will call first(), thread B will call second(), and thread C will call third(). Design a mechanism and modify the program to ensure that second() is executed after first(), and third() is executed after second().

Example 1:

``````Input: [1,2,3]
Output: "firstsecondthird"
Explanation: There are three threads being fired asynchronously. The input [1,2,3] means thread A calls first(), thread B calls second(), and thread C calls third(). "firstsecondthird" is the correct output.
``````

Example 2:

``````Input: [1,3,2]
Output: "firstsecondthird"
Explanation: The input [1,3,2] means thread A calls first(), thread B calls third(), and thread C calls second(). "firstsecondthird" is the correct output.

``````

Note:

We do not know how the threads will be scheduled in the operating system, even though the numbers in the input seems to imply the ordering. The input format you see is mainly to ensure our tests’ comprehensiveness.

Java解法如下：

``````class Foo {
private final AtomicInteger i = new AtomicInteger();
private final Object lock = new Object();

public Foo() {
i.set(0);
}

public void first(Runnable printFirst) throws InterruptedException {
synchronized (lock) {
while (i.get() != 0) {
lock.wait();
}
printFirst.run();
i.set(1);
lock.notifyAll();
}
}

public void second(Runnable printSecond) throws InterruptedException {
synchronized (lock) {
while (i.get() != 1) {
lock.wait();
}
printSecond.run();
i.set(2);
lock.notifyAll();
}
}

public void third(Runnable printThird) throws InterruptedException {
synchronized (lock) {
while (i.get() != 2) {
lock.wait();
}
printThird.run();
i.set(3);
}
}
}
``````