I am solving a LeetCode problem from this link: https://leetcode.com/problems/fizz-buzz-multithreaded/.
Basically, I am writing a FizzBuzz class that does the standard fizzbuzz, but with 4 threads running at the same time, each calling different methods. (one thread is calling fizzbuzz, one calling fizz, one calling buzz, and one calling number). Here is my solution which is accepted:
class FizzBuzz {
private int n;
int num = 1; // FizzBuzz starts at 1.
public FizzBuzz(int n) {
this.n = n;
}
// printFizz.run() outputs "fizz".
public synchronized void fizz(Runnable printFizz) throws InterruptedException {
while(num <= n) {
if(num % 3 == 0 && num % 5 != 0) {
printFizz.run();
num++;
notifyAll();
} else {
wait();
}
}
}
// printBuzz.run() outputs "buzz".
public synchronized void buzz(Runnable printBuzz) throws InterruptedException {
while(num <= n) {
if(num % 3 != 0 && num % 5 == 0) {
printBuzz.run();
num++;
notifyAll();
} else {
wait();
}
}
}
// printFizzBuzz.run() outputs "fizzbuzz".
public synchronized void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {
while(num <= n) {
if(num % 15 == 0) {
printFizzBuzz.run();
num++;
notifyAll();
} else {
wait();
}
}
}
// printNumber.accept(x) outputs "x", where x is an integer.
public synchronized void number(IntConsumer printNumber) throws InterruptedException {
while(num <= n) {
if(num % 3 != 0 && num % 5 != 0) {
printNumber.accept(num);
num++;
notifyAll();
} else {
wait();
}
}
}
}
The problem is I am having difficulty simulating the situation in my IDE.
This is my main method:
public class FizzBuzzMain {
public static void main(String[] args) {
FizzBuzz fizzBuzz = new FizzBuzz(15);
Runnable printFizzBuzz = new PrintFizzBuzz();
Runnable printFizz = new PrintFizz();
Runnable printBuzz = new PrintBuzz();
Thread t1 = new Thread(printFizzBuzz);
Thread t2 = new Thread(printFizz);
Thread t3 = new Thread(printBuzz);
IntConsumer printNumber = new PrintNumber();
t1.start();
t2.start();
t3.start();
try {
fizzBuzz.number(printNumber);
fizzBuzz.fizz(printFizz);
fizzBuzz.buzz(printBuzz);
fizzBuzz.buzz(printFizzBuzz);
} catch(Exception e) {
e.printStackTrace();
}
}
}
I'd like to initialize fourth thread with IntConsumer (this is given from the question), so that I can execute t4 as well, but I am not sure how to do that. Obviously, my main method stops running at some point since all threads go to wait state and no one is waking them up (t4 is missing here).
Any help would be greatly appreciated!