
























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:
A will call foo(), whileB 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.
Constraints:
1 <= n <= 1000The requirement:
foo()bar()The key problem is: how do we make one thread wait until it is its turn?
Semaphore (Recommended)Use two semaphores:
foo_sem: controls when foo() can runbar_sem: controls when bar() can runInitial state:
Flow:
Initial:
Foo thread:
State:
Bar thread:
State:
Repeat.
Output:
You can also solve it using Condition.
Maintain a shared variable:
Foo waits until:
Bar waits until:
Both work, but they model the problem differently.
You are saying:
"Foo has a permit to print. After printing, give the permit to Bar."
The semaphore itself stores the state.
Very natural for alternating execution.
You are saying:
"Threads should wait until the shared state
foo_turnchanges."
The state is external:
The condition only wakes threads.
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。