## 题目描述：

LeetCode 1115. Print FooBar Alternately

Suppose you are given the following code:

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");
}
}
}

The same instance of FooBar will be passed to two different threads. Thread A will call foo() while thread B will call bar(). Modify the given program to output "foobar" n times.

Example 1:

Input: n = 1
Output: "foobar"
Explanation: There are two threads being fired asynchronously. One of them calls foo(), while the other calls bar(). "foobar" is being output 1 time.

Example 2:

Input: n = 2
Output: "foobarfoobar"
Explanation: "foobar" is being output 2 times.

## 解题思路：

A counting semaphore. Conceptually, a semaphore maintains a set ofpermits. Each acquire blocks if necessary until a permit isavailable, and then takes it. Each release adds a permit,potentially releasing a blocking acquirer.However, no actual permit objects are used; the Semaphore justkeeps a count of the number available and acts accordingly.

foo方法输出Foo之前 acquire semaphoreFoo，之后 release semaphoreBar

bar方法反之。

## Java代码：

import java.util.concurrent.Semaphore;
class FooBar {
private Semaphore semaphoreFoo, semaphoreBar;
private int n;

public FooBar(int n) {
this.semaphoreFoo = new Semaphore(1);
this.semaphoreBar = new Semaphore(0);
this.n = n;
}

public void foo(Runnable printFoo) throws InterruptedException {

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

public void bar(Runnable printBar) throws InterruptedException {

for (int i = 0; i < n; i++) {
this.semaphoreBar.acquire();
// printBar.run() outputs "bar". Do not change or remove this line.
printBar.run();
this.semaphoreFoo.release();
}
}
}

Pingbacks已关闭。