LeetCode(多线程)- 1114. 按序打印
Posted 程序员牧码
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode(多线程)- 1114. 按序打印相关的知识,希望对你有一定的参考价值。
题目链接:点击打开链接
题目大意:略。
解题思路:略。
相关企业
- 爱奇艺
- 微软(Microsoft)
AC 代码
// 解决方案(1)
class Foo
public Foo()
volatile int count=1;
public void first(Runnable printFirst) throws InterruptedException
printFirst.run();
count++;
public void second(Runnable printSecond) throws InterruptedException
while (count!=2);
printSecond.run();
count++;
public void third(Runnable printThird) throws InterruptedException
while (count!=3);
printThird.run();
// 解决方案(2)
class Foo
private boolean firstFinished;
private boolean secondFinished;
private Object lock = new Object();
public Foo()
public void first(Runnable printFirst) throws InterruptedException
synchronized (lock)
// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
firstFinished = true;
lock.notifyAll();
public void second(Runnable printSecond) throws InterruptedException
synchronized (lock)
while (!firstFinished)
lock.wait();
// printSecond.run() outputs "second". Do not change or remove this line.
printSecond.run();
secondFinished = true;
lock.notifyAll();
public void third(Runnable printThird) throws InterruptedException
synchronized (lock)
while (!secondFinished)
lock.wait();
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();
以上是关于LeetCode(多线程)- 1114. 按序打印的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode刷题 多线程编程九则 | 1188. 设计有限阻塞队列 1242. 多线程网页爬虫 1279. 红绿灯路口