Suppose you are given the following code:1
2
3
4
5
6
7
8
9
10
11
12
13class 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
3Input: n = 2
Output: "foobarfoobar"
Explanation: "foobar" is being output 2 times.
1 | import java.util.concurrent.Semaphore; |
从 Semaphore bar = new Semaphore(0);
和后面的bar.release();
可以看出来,bar
一开始初始化为0
只是表明不能直接用,而不是说整个信道permit的数量都最多不超过0: bar.release()
就创建了一个。只是表明一开始为0,不能直接用