## 题目描述：

LeetCode 1114. Print in Order

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 `three()`. 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.

## 解题思路：

CountDownLatch （倒数计数锁存器）

A CountDownLatch is initialized with a given count.The await methods block until the current count reacheszero due to invocations of the countDown method, after whichall waiting threads are released and any subsequent invocations of await return immediately. This is a one-shot phenomenon-- the count cannot be reset. If you need a version that resets thecount, consider using a CyclicBarrier.

```初始化两个CountDownLatch countDownLatch1和countDownLatch2。初始计数分别为1和2。

first方法执行时对countDownLatch1和countDownLatch2都执行countDown。此时await在countDownLatch1的second方法会被唤醒。在second方法执行的末尾对countDownLatch2执行countDown，此时third方法会被唤醒。```

## Java代码：

``````import java.util.concurrent.CountDownLatch;

class Foo {

CountDownLatch countDownLatch1;
CountDownLatch countDownLatch2;
public Foo() {
countDownLatch1 = new CountDownLatch(1);
countDownLatch2 = new CountDownLatch(2);
}

public void first(Runnable printFirst) throws InterruptedException {

// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
countDownLatch1.countDown();
countDownLatch2.countDown();
}

public void second(Runnable printSecond) throws InterruptedException {

countDownLatch1.await();
// printSecond.run() outputs "second". Do not change or remove this line.
printSecond.run();
countDownLatch2.countDown();
}

public void third(Runnable printThird) throws InterruptedException {
countDownLatch2.await();
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();
}
}
``````

Pingbacks已关闭。