题目描述:
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.
题目大意:
类Foo有三个方法first, second和third。其实例被传给三个线程A, B和C。分别调用first, second和third方法。
设计机制使得first先调用,second其次,third最后。
解题思路:
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。 在second方法中对countDownLatch1进行await,在third方法中对countDownLatch2进行await。 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();
}
}
本文链接:http://bookshadow.com/weblog/2019/07/14/leetcode-print-in-order/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。