★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(let_us_code)
➤博主域名:https://www.zengqiang.org
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/11565806.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
Write a program that outputs the string representation of numbers from 1 to n, however:
- If the number is divisible by 3, output "fizz".
- If the number is divisible by 5, output "buzz".
- If the number is divisible by both 3 and 5, output "fizzbuzz".
For example, for n = 15
, we output: 1, 2, fizz, 4, buzz, fizz, 7, 8, fizz, buzz, 11, fizz, 13, 14, fizzbuzz
.
Suppose you are given the following code:
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 }
Implement a multithreaded version of FizzBuzz
with four threads. The same instance of FizzBuzz
will be passed to four different threads:
- Thread A will call
fizz()
to check for divisibility of 3 and outputsfizz
. - Thread B will call
buzz()
to check for divisibility of 5 and outputsbuzz
. - Thread C will call
fizzbuzz()
to check for divisibility of 3 and 5 and outputsfizzbuzz
. - Thread D will call
number()
which should only output the numbers.
1 class FizzBuzz { 2 3 private int n; 4 private int currentNumber = 1; 5 6 public FizzBuzz(int n) { 7 this.n = n; 8 } 9 10 // printFizz.run() outputs "fizz". 11 public synchronized void fizz(Runnable printFizz) throws InterruptedException { 12 while (currentNumber <= n) { 13 if (currentNumber % 3 != 0 || currentNumber % 5 == 0) { 14 wait(); 15 continue; 16 } 17 printFizz.run(); 18 currentNumber += 1; 19 notifyAll(); 20 } 21 } 22 23 // printBuzz.run() outputs "buzz". 24 public synchronized void buzz(Runnable printBuzz) throws InterruptedException { 25 while (currentNumber <= n) { 26 if (currentNumber % 5 != 0 || currentNumber % 3 == 0) { 27 wait(); 28 continue; 29 } 30 printBuzz.run(); 31 currentNumber += 1; 32 notifyAll(); 33 } 34 } 35 36 // printFizzBuzz.run() outputs "fizzbuzz". 37 public synchronized void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException { 38 while (currentNumber <= n) { 39 if (currentNumber % 15 != 0) { 40 wait(); 41 continue; 42 } 43 printFizzBuzz.run(); 44 currentNumber += 1; 45 notifyAll(); 46 } 47 } 48 49 // printNumber.accept(x) outputs "x", where x is an integer. 50 public synchronized void number(IntConsumer printNumber) throws InterruptedException { 51 while (currentNumber <= n) { 52 if (currentNumber % 3 == 0 || currentNumber % 5 == 0) { 53 wait(); 54 continue; 55 } 56 printNumber.accept(currentNumber); 57 currentNumber += 1; 58 notifyAll(); 59 } 60 } 61 }