题目描述
我们提供了一个类:
|
1
2
3
4
5
|
public class Foo {
public void one() { print("one"); }
public void two() { print("two"); }
public void three() { print("three"); }
} |
三个不同的线程将会共用一个 Foo 实例。
线程 A 将会调用 one() 方法
线程 B 将会调用 two() 方法
线程 C 将会调用 three() 方法
请设计修改程序,以确保 two() 方法在 one() 方法之后被执行,three() 方法在 two() 方法之后被执行。
示例 1:
输入: [1,2,3]
输出: "onetwothree"
解释:
有三个线程会被异步启动。
输入 [1,2,3] 表示线程 A 将会调用 one() 方法,线程 B 将会调用 two() 方法,线程 C 将会调用 three() 方法。
正确的输出是 "onetwothree"。
题目分析
two() 方法在 one() 方法之后被执行,three() 方法在 two() 方法之后被执行,即two、three的前置任务(线程)均有1个,我们可以引入倒计时器,并初始化其值为1。
这样,每当one完成后,two被唤醒,每当two完成后,three被唤醒。
Java题解
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
import java.util.concurrent.CountDownLatch;
class Foo {
private CountDownLatch count_a = new CountDownLatch(1);
private CountDownLatch count_b = new CountDownLatch(1);
public Foo() {
}
public void first(Runnable printFirst) throws InterruptedException {
// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
count_a.countDown();
}
public void second(Runnable printSecond) throws InterruptedException {
count_a.await();
// printSecond.run() outputs "second". Do not change or remove this line.
printSecond.run();
count_b.countDown();
}
public void third(Runnable printThird) throws InterruptedException {
count_b.await();
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();
}
} |