leetcode 1115. 交替打印FooBar(多线程编程)

本文介绍如何使用Java的互斥锁(mutex)在FooBar类的foo和bar方法中实现线程同步,确保当两个线程交替调用时,'foobar'字符串总共输出n次。通过使用m1和m2锁,防止竞态条件并保证输出顺序。
摘要由CSDN通过智能技术生成

题目:
我们提供一个类:

class FooBar {
  public void foo() {
    for (int i = 0; i < n; i++) {
      print("foo");
    }
  }

  public void bar() {
    for (int i = 0; i < n; i++) {
      print("bar");
    }
  }
}

两个不同的线程将会共用一个 FooBar 实例。其中一个线程将会调用 foo() 方法,另一个线程将会调用 bar() 方法。

请设计修改程序,以确保 “foobar” 被输出 n 次。

示例 1:
输入: n = 1
输出: "foobar"
解释: 这里有两个线程被异步启动。其中一个调用 foo() 方法, 另一个调用 bar() 方法,"foobar" 将被输出一次。

思路解析:
使用mutex加锁解锁,两个线程不能同时进入加锁空间,待一个线程使用结束解锁后另一个线程才能被调用。
代码实现:

class FooBar {
private:
    int n;

public:
    mutex m1,m2;
    FooBar(int n) {
        this->n = n;
    }
    FooBar()
    {
        m1.lock();
        m2.lock();
    }

    void foo(function<void()> printFoo) {
        
        for (int i = 0; i < n; i++) {
            m2.lock();
        	// printFoo() outputs "foo". Do not change or remove this line.
        	printFoo();
            m1.unlock();
        }
    }

    void bar(function<void()> printBar) {
        
        for (int i = 0; i < n; i++) {
            m1.lock();
        	// printBar() outputs "bar". Do not change or remove this line.
        	printBar();
            m2.unlock();
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值