前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode多线程之交替打印FooBar

leetcode多线程之交替打印FooBar

原创
作者头像
code4it
修改2020-09-08 10:18:33
7950
修改2020-09-08 10:18:33
举报
文章被收录于专栏:码匠的流水账码匠的流水账

本文主要记录一下leetcode多线程之交替打印FooBar

题目

代码语言:javascript
复制
我们提供一个类:
​
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 次。
​
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/print-foobar-alternately
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解

代码语言:javascript
复制
class FooBar {
    private int n;
​
    ReentrantLock lock = new ReentrantLock();
    Condition fooCnd = lock.newCondition();
    Condition barCnd = lock.newCondition();
​
    boolean foo = true;
​
    public FooBar(int n) {
        this.n = n;
    }
​
    public void foo(Runnable printFoo) throws InterruptedException {
        
        lock.lock();
        try {
            for (int i = 0; i < n; i++) {
                if (!foo) {
                    fooCnd.await();
                }
                foo = false;
                // printFoo.run() outputs "foo". Do not change or remove this line.
                printFoo.run();
                barCnd.signal();
            }
        } finally {
            lock.unlock();
        }
    }
​
    public void bar(Runnable printBar) throws InterruptedException {
        
        lock.lock();
        try {
            for (int i = 0; i < n; i++) {
                if (foo) {
                    barCnd.await();
                }
                foo = true;
                // printBar.run() outputs "bar". Do not change or remove this line.
                printBar.run();
                fooCnd.signal();
            }
        } finally {
            lock.unlock();
        }
    }
}
  • 这里使用ReentrantLock的condition来进行条件控制

小结

因为这里要循环多次打印,因而选择了ReentrantLock的condition来进行条件控制

doc

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 题解
  • 小结
  • doc
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档