LeetCode(多线程)- 1114. 按序打印

简介: 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();
        } 
    }
}
目录
相关文章
|
12月前
|
数据采集 负载均衡 安全
LeetCode刷题 多线程编程九则 | 1188. 设计有限阻塞队列 1242. 多线程网页爬虫 1279. 红绿灯路口
本文提供了多个多线程编程问题的解决方案,包括设计有限阻塞队列、多线程网页爬虫、红绿灯路口等,每个问题都给出了至少一种实现方法,涵盖了互斥锁、条件变量、信号量等线程同步机制的使用。
182 3
LeetCode刷题 多线程编程九则 | 1188. 设计有限阻塞队列 1242. 多线程网页爬虫 1279. 红绿灯路口
Leetcode之多线程编程题
现有函数 printNumber 可以用一个整数参数调用,并输出该整数到控制台。 例如,调用 printNumber(7) 将会输出 7 到控制台。 给你类 ZeroEvenOdd 的一个实例,该类中有三个函数:zero、even 和 odd 。ZeroEvenOdd 的相同实例将会传递给三个不同线程:
198 1
|
数据采集
LeetCode(多线程)- 1242. 多线程网页爬虫
LeetCode(多线程)- 1242. 多线程网页爬虫
339 0
|
调度
leetcode.1114-按序打印-多线程案例
leetcode.1114-按序打印-多线程案例
153 0
leetcode线程题1116——打印零与奇偶数
leetcode线程题1116——打印零与奇偶数
136 0
leetcode线程题1117——H2O 生成(两个氢原子结合一个氧原子)
leetcode线程题1117——H2O 生成(两个氢原子结合一个氧原子)
251 0
|
调度
leetcode 线程题 1114. 按序打印
leetcode 线程题 1114. 按序打印
LeetCode(多线程)- 题集
LeetCode(多线程)- 题集
159 0
LeetCode(多线程)- 题集
LeetCode(多线程)- 1279. 红绿灯路口
LeetCode(多线程)- 1279. 红绿灯路口
414 0
LeetCode(多线程)- 1226. 哲学家进餐
LeetCode(多线程)- 1226. 哲学家进餐
145 0

热门文章

最新文章