Print FooBar Alternately
MediumConcurrencySemaphoreMutexThread CoordinationCondition Variable
Problem Statement
You are given a class FooBar with two methods: foo() and bar(). Two threads — Thread A and Thread B — will concurrently call foo() and bar() respectively. Your task is to synchronize them so that the output is always "foobar" repeated exactly n times.
class FooBar {
private int n;
public FooBar(int n) { this.n = n; }
public void foo(Runnable printFoo) throws InterruptedException {
// printFoo.run() outputs "foo"
}
public void bar(Runnable printBar) throws InterruptedException {
// printBar.run() outputs "bar"
}
}
Key Entities
- FooBar: Shared state object holding iteration counter
n. - Semaphore pair: Two semaphores (one starting at 1, one at 0) enabling ping-pong signaling.
- Condition Variables: Alternative to semaphores for signaling between foo and bar.
Requirements
- Output must always be
"foobar"repeated exactlyntimes — never"barfoo"or interleaved. - Thread A only calls
foo()and Thread B only callsbar(). - No busy-waiting allowed.
- Solution must handle
nup to 1,000.
Asked at: Google, Amazon, Microsoft, Facebook, Uber
!Constraints
- 1 ≤ n ≤ 1000
- Exactly two threads: one calls foo(), the other calls bar().
- Output must be exactly "foobar" * n with no extra characters.
- No busy-waiting or Thread.sleep() for synchronization.
Output
Run or submit your code to see output here.