leecode-1115:交替打印FooBar

题目描述

我们提供一个类:

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" 将被输出一次。

示例 2:

输入: n = 2
输出: "foobarfoobar"
解释: "foobar" 将被输出两次。

分析

由题意可知,我们需要将foo bar 按照顺序打印,并且要打印n次。回想第1114题目1114:按序打印,我们知道JUC包下的三个工具类,由此我们可以想到使用Semaphore信号量,来控制线程的执行权限。

代码实现

初始信号量为0,则可以执行代码块,如果不为0则需要等待为0。
release() 释放 -> 信号量-1
acquire() 获取 -> 信号量+1

而且置为0,线程不会释放,会进入下一个循环。

import java.util.concurrent.Semaphore;

class FooBar {
    private int n;
    private Semaphore semaphoreFoo = new Semaphore(0);
    private Semaphore semaphoreBar = new Semaphore(0);

    public FooBar(int n) {
        this.n = n;
    }

    public void foo(Runnable printFoo) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            // printFoo.run() outputs "foo". Do not change or remove this line.
            printFoo.run();
            semaphoreBar.release(); // bar信号量为-1
            semaphoreFoo.acquire(); // foo信号量为1
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            semaphoreBar.acquire();// bar信号量为0,可以执行
            // printBar.run() outputs "bar". Do not change or remove this line.
            printBar.run();
            semaphoreFoo.release();// foo信号量为0,可以执行其它线程
        }
    }
}

总结

根据Semaphore的可循环特性,可以很好的解决此类问题。

你可能感兴趣的:(leecode-1115:交替打印FooBar)