1114-按序打印
文章目录
前言
我们提供了一个类:
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"。示例2:
输入: [1,3,2] 输出: "onetwothree" 解释: 输入 [1,3,2] 表示线程 A 将会调用 one() 方法,线程 B 将会调用 three() 方法,线程 C 将会调用 two() 方法。 正确的输出是 "onetwothree"。提示:
尽管输入中的数字似乎暗示了顺序,但是我们并不保证线程在操作系统中的调度顺序。你看到的输入格式主要是为了确保测试的全面性。
解题思路
本题的题目其实很容易,题目描述的很清楚。我选择的是使用while死循环结合一个int变量控制对应的线程进行打印。需要注意int变量需要使用volatile修饰确保其的可见性和有序性。
实现代码
/**
* 1114. 按序打印
* @author NULL
* @see <a href="https://leetcode-cn.com/problems/print-in-order/">1114. 按序打印</a>
* @date 2019-09-08
*/
class Foo {
/**
* 当前应该打印的线程
*/
private volatile int status = 1;
public Foo() {
}
public void first(Runnable printFirst) throws InterruptedException {
while(status==1){
// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
status=2;
}
}
public void second(Runnable printSecond) throws InterruptedException {
while (status!=2){
// 此处不等于2则死循环等待
}
// printSecond.run() outputs "second". Do not change or remove this line.
printSecond.run();
status=3;
}
public void third(Runnable printThird) throws InterruptedException {
while (status!=3){
// 此处不等于3则死循环等待
}
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();
status=1;
}
}

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论