Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情。
leetcode刷题1114按序打印
前文
本文为leetcode多线程类型题目,题目序号为1114,主要考察对于多线程知识的应用。
题目内容
给你一个类:
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() 方法之后被执行。
解题思路分析
这道题根据题目信息,很容易知道考察的内容为对于多线程知识的运用,尤其是对于线程执行顺序的控制。根据题目的要求,我们需要保证的是方法二永远在方法一之后执行,方法三永远在方法二之后执行。显然,这里可以轻易想到通过线程控制关键字CountDownLatch操作。该关键字指定了只有当某些线程执行完成后才可以执行后续操作。因此只需要应用两次该关键字,我们即可得到题目答案。
解题代码
class Foo {
CountDownLatch countDownLatch1 = new CountDownLatch(1);
CountDownLatch countDownLatch2 = 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();
countDownLatch1.countDown();
}
public void second(Runnable printSecond) throws InterruptedException {
// printSecond.run() outputs "second". Do not change or remove this line.
countDownLatch1.await();
printSecond.run();
countDownLatch2.countDown();
}
public void third(Runnable printThird) throws InterruptedException {
// printThird.run() outputs "third". Do not change or remove this line.
countDownLatch2.await();
printThird.run();
}
}
后记
- 千古兴亡多少事?悠悠。不尽长江滚滚流。