# LEETCODE 1195. Fizz Buzz Multithreaded 解题思路分析

`class FizzBuzz {   public FizzBuzz(int n) { … }  // constructor public void fizz(printFizz) { … } // only output "fizz" public void buzz(printBuzz) { … } // only output "buzz" public void fizzbuzz(printFizzBuzz) { … } // only output "fizzbuzz" public void number(printNumber) { … } // only output the numbers }`

1. 线程A将调用 fizz() 来判断是否能被 3 整除，如果可以，则输出 fizz。
2. 线程B将调用 buzz() 来判断是否能被 5 整除，如果可以，则输出 buzz。
3. 线程C将调用 fizzbuzz() 来判断是否同时能被 3 和 5 整除，如果可以，则输出 fizzbuzz。
4. 线程D将调用 number() 来实现输出既不能被 3 整除也不能被 5 整除的数字。

```private int n;
Semaphore fizz = new Semaphore(0);
Semaphore buzz = new Semaphore(0);
Semaphore fizzbuzz = new Semaphore(0);
Semaphore number = new Semaphore(1);
public FizzBuzz(int n) {
this.n = n;
}

// printFizz.run() outputs "fizz".
public void fizz(Runnable printFizz) throws InterruptedException {
for(int i= 1;i<=n;i++){
if(i % 3 ==0 && i%5!=0){
fizz.acquire();
printFizz.run();
releaseNext(i+1);
}
}
}

// printBuzz.run() outputs "buzz".
public void buzz(Runnable printBuzz) throws InterruptedException {
for(int i= 1;i<=n;i++){
if(i % 5 ==0 && i%3!=0){
buzz.acquire();
printBuzz.run();
releaseNext(i+1);
}
}
}

// printFizzBuzz.run() outputs "fizzbuzz".
public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {
for(int i= 1;i<=n;i++){
if(i % 5 ==0 && i%3==0){
fizzbuzz.acquire();
printFizzBuzz.run();
releaseNext(i+1);
}
}
}

// printNumber.accept(x) outputs "x", where x is an integer.
public void number(IntConsumer printNumber) throws InterruptedException {
for(int i= 1;i<=n;i++){
if(i % 5 !=0 && i%3!=0){
number.acquire();
printNumber.accept(i);
releaseNext(i+1);
}
}
}

private void releaseNext(int i){
if(i>n){
return;
}
if(i % 3 ==0 && i%5==0){
fizzbuzz.release();
}else if(i % 3==0){
fizz.release();
}else if(i % 5==0){
buzz.release();
}else{
number.release();
}
}```

Runtime: 4 ms, faster than 99.88% of Java online submissions for Fizz Buzz Multithreaded.

Memory Usage: 36 MB, less than 100.00% of Java online submissions for Fizz Buzz Multithreaded.