You're given a FooBar class that contains two methods: foo() and bar(). Each method runs in a loop n times, printing either "foo" or "bar" respectively.
The challenge is that the same instance of FooBar will be accessed by two different threads simultaneously:
- Thread A will call
foo() - Thread B will call
bar()
Your task is to modify the class to ensure that the output is always "foobar" repeated n times, with proper alternation between the two strings.
Example: If n=3, the expected output should be: foobarfoobarfoobar
This is a classic thread synchronization problem where you need to coordinate two threads to produce alternating output in the correct order.
Input & Output
Time & Space Complexity
Each thread executes n times with minimal synchronization overhead, no busy waiting
Only one mutex, one condition variable, and one boolean state variable needed
Constraints
- 1 โค n โค 1000
- Two threads will call foo() and bar() concurrently
- Output must be exactly 'foobar' repeated n times
- No other output patterns are acceptable