题目描述:
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.
题目大意:
交替输出Foo和Bar。
解题思路:
信号量(Semahpore)
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.
初始化两个信号量semaphoreFoo和semaphoreBar,permits分别为1和0。
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();
}
}
}
本文链接:http://bookshadow.com/weblog/2019/07/15/leetcode-print-foobar-alternately/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。