Print FizzBuzz Multithreaded
MediumConcurrencySemaphoreMutexThread CoordinationCondition Variable
Problem Statement
Design a multithreaded solution that outputs the FizzBuzz sequence from 1 to n using exactly four threads.
- Thread A calls
fizz()— prints "fizz" for numbers divisible by 3 (but not 5). - Thread B calls
buzz()— prints "buzz" for numbers divisible by 5 (but not 3). - Thread C calls
fizzbuzz()— prints "fizzbuzz" for numbers divisible by both 3 and 5. - Thread D calls
number()— prints the number itself for all other integers.
class FizzBuzz {
private int n;
public FizzBuzz(int n) { this.n = n; }
public void fizz(Runnable printFizz) throws InterruptedException {}
public void buzz(Runnable printBuzz) throws InterruptedException {}
public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {}
public void number(IntConsumer printNumber) throws InterruptedException {}
}
Key Entities
- FizzBuzz: Shared counter and synchronization logic.
- Four specialized threads: Each dedicated to one output type.
- Semaphores / ReentrantLock+Condition: Four semaphores (one per thread type) controlling which thread wakes.
Requirements
- Output must be perfectly ordered from 1 to n.
- All four threads must participate — no thread may handle multiple conditions.
- Each number must be processed exactly once.
- No busy-waiting.
Asked at: Google, Amazon, Microsoft, Apple, Goldman Sachs
!Constraints
- 1 ≤ n ≤ 50
- Exactly four threads — one per method.
- Output sequence must match single-threaded FizzBuzz exactly.
- Threads call their assigned methods in a loop until n is exhausted.
Output
Run or submit your code to see output here.