Suppose you are given the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
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
2
3
Input: n = 2
Output: "foobarfoobar"
Explanation: "foobar" is being output 2 times.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import java.util.concurrent.Semaphore;

class FooBar {
private int n;
Semaphore bar = new Semaphore(0);
Semaphore foo = new Semaphore(1);

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.
foo.acquire();
printFoo.run();
bar.release();
}
}

public void bar(Runnable printBar) throws InterruptedException {

for (int i = 0; i < n; i++) {

// printBar.run() outputs "bar". Do not change or remove this line.
bar.acquire();
printBar.run();
foo.release();
}
}
}

Semaphore bar = new Semaphore(0);和后面的bar.release();可以看出来,bar一开始初始化为0只是表明不能直接用,而不是说整个信道permit的数量都最多不超过0: bar.release()就创建了一个。只是表明一开始为0,不能直接用