多线程顺序打印

1、描述

我们提供了一个类:

public class Foo {
public void first() { print(“first”); }
public void second() { print(“second”); }
public void third() { print(“third”); }
}
三个不同的线程 A、B、C 将会共用一个 Foo 实例。

一个将会调用 first() 方法
一个将会调用 second() 方法
还有一个将会调用 third() 方法
请设计修改程序,以确保 second() 方法在 first() 方法之后被执行,third() 方法在 second() 方法之后被执行。

来源:力扣(LeetCode)
链接:

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2、关键字

顺序打印,多线程

3、思路

互斥锁
条件变量解法参考

4、notes

新知识点:
条件变量:
condition_variable cv;
mutex mtx;
int k = 0;
写在类里边;

5、复杂度

6、code

class Foo {
public:
    condition_variable cv;  // 条件变量
    mutex mtx;  // 锁
    int k = 0;
    Foo() { }

    void first(function<void()> printFirst) {              
        printFirst();
        k = 1;
        cv.notify_all(); // 通知其他所有在等待唤醒队列中的线程
    }

    void second(function<void()> printSecond) {
        unique_lock<mutex>lock(mtx);
        cv.wait(lock, [this](){return k == 1;});
        k = 2;
        //cv.notify_all();  // 也行
        cv.notify_one();    // 随机通知一个(unspecified)在等待唤醒队列中的线程
        printSecond();
    }

    void third(function<void()> printThird) {
        unique_lock<mutex>lock(mtx);
        cv.wait(lock, [this](){return k == 2;});        
        printThird();
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值