Print FooBar Alternately

Medium
ConcurrencySemaphoreMutexThread 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

  1. Output must always be "foobar" repeated exactly n times — never "barfoo" or interleaved.
  2. Thread A only calls foo() and Thread B only calls bar().
  3. No busy-waiting allowed.
  4. Solution must handle n up 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.