The single-threaded FizzBuzz is a warm-up question. The multithreaded version is a real concurrency exercise: four separate threads must cooperate to produce the FizzBuzz sequence for 1..n in order, even though no single thread sees every number.
Implement FizzBuzz(n) with four methods, each run on its own thread. Each method is handed a callback and must invoke it at exactly the right moments, in ascending order:
fizz(printFizz) — call printFizz() for every i divisible by 3 but not 5buzz(printBuzz) — call printBuzz() for every i divisible by 5 but not 3fizzbuzz(printFizzBuzz) — call printFizzBuzz() for every i divisible by both 3 and 5number(printNumber) — call printNumber(i) for every i divisible by neitherThe four threads run concurrently, so you must synchronize them: the combined sequence of callback invocations must be exactly the FizzBuzz output for 1..n, with no gaps, duplicates, or out-of-order emissions.
Example (n = 15): the callbacks together must produce
1, 2, fizz, 4, buzz, fizz, 7, 8, fizz, buzz, 11, fizz, 13, 14, fizzbuzz
Constraints:
1 <= n <= 1000threading primitives only (Condition, Lock, Event, Semaphore)Official solution locked
Give the problem a real attempt before peeking — revealing it affects your credit for this problem for 4 hours.