Welcome to the world of multithreaded programming! This problem combines the classic FizzBuzz game with concurrent execution, creating a fascinating challenge in thread synchronization.
You're given a FizzBuzz class that needs to coordinate four different threads to produce the correct output sequence. Each thread has a specific responsibility:
- Thread A: Calls
fizz()to print "fizz" when numbers are divisible by 3 but not 5 - Thread B: Calls
buzz()to print "buzz" when numbers are divisible by 5 but not 3 - Thread C: Calls
fizzbuzz()to print "fizzbuzz" when numbers are divisible by both 3 and 5 - Thread D: Calls
number()to print the actual number when it's not divisible by 3 or 5
The challenge is to synchronize these threads so they output the sequence [1, 2, "fizz", 4, "buzz", "fizz", 7, 8, "fizz", "buzz", 11, "fizz", 13, 14, "fizzbuzz", ...] in the correct order, despite running concurrently.
Goal: Implement thread synchronization mechanisms to ensure the output appears in sequential order from 1 to n.
Input & Output
Visualization
Time & Space Complexity
Each number is processed exactly once with efficient waiting
Uses only synchronization primitives and a counter
Constraints
- 1 โค n โค 50
- Four threads will be created to call the four functions concurrently
- The same instance of FizzBuzz will be passed to all four threads
- Thread safety is required - output must be in correct sequential order