LC1114.按序打印

1114. 按序打印

题目描述

给你一个类:

1
2
3
4
5
public class Foo {
public void first() { print("first"); }
public void second() { print("second"); }
public void third() { print("third"); }
}

三个不同的线程 A、B、C 将会共用一个 Foo 实例。

  • 线程 A 将会调用 first() 方法
  • 线程 B 将会调用 second() 方法
  • 线程 C 将会调用 third() 方法

请设计修改程序,以确保 second() 方法在 first() 方法之后被执行,third() 方法在 second() 方法之后被执行。

提示:

  • 尽管输入中的数字似乎暗示了顺序,但是我们并不保证线程在操作系统中的调度顺序。
  • 你看到的输入格式主要是为了确保测试的全面性。

示例 1:

1
2
3
4
输入:nums = [1,2,3]
输出:"firstsecondthird"
解释:
有三个线程会被异步启动。输入 [1,2,3] 表示线程 A 将会调用 first() 方法,线程 B 将会调用 second() 方法,线程 C 将会调用 third() 方法。正确的输出是 "firstsecondthird"

示例 2:

1
2
3
4
输入:nums = [1,3,2]
输出:"firstsecondthird"
解释:
输入 [1,3,2] 表示线程 A 将会调用 first() 方法,线程 B 将会调用 third() 方法,线程 C 将会调用 second() 方法。正确的输出是 "firstsecondthird"

提示:

  • nums[1, 2, 3] 的一组排列

思路

任务一、任务二和任务三之间是同步关系。

任务二需要在任务一完成后执行,任务三需要在任务二完成后执行。

可以使用两个信号量来解决这个问题。

  • firstDone: 表示任务一已经完成,初始值为 0
  • secondDone: 表示任务二已经完成,初始值为 0
1
2
3
4
Job1 {
执行任务一
V(firstDone)
}
1
2
3
4
5
Job2 {
P(firstDone)
执行任务二
V(secondDone)
}
1
2
3
4
Job3 {
P(secondDone)
执行任务三
}

代码

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
32
33
34
35
36
class Foo {
private AtomicInteger firstDone = new AtomicInteger(0);
private AtomicInteger secondDone = new AtomicInteger(0);

public Foo() {

}

public void first(Runnable printFirst) throws InterruptedException {

// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
// 第一个任务执行完成
firstDone.incrementAndGet();
}

public void second(Runnable printSecond) throws InterruptedException {
// 等待第一个任务执行完成
while (firstDone.get() != 1) {

}
// printSecond.run() outputs "second". Do not change or remove this line.
printSecond.run();
// 第二个任务执行完成
secondDone.incrementAndGet();
}

public void third(Runnable printThird) throws InterruptedException {
// 等待第二个任务执行完成
while (secondDone.get() != 1) {

}
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();
}
}

LC1114.按序打印
https://liuyuhe666.github.io/2025/01/05/LC1114-按序打印/
作者
Liu Yuhe
发布于
2025年1月5日
许可协议