原题连接leetcode1195
题目描述:
编写一个可以从 1 到 n 输出代表这个数字的字符串的程序,但是:
例如,当 n = 15,输出: 1, 2, fizz, 4, buzz, fizz, 7, 8, fizz, buzz, 11, fizz, 13, 14, fizzbuzz。
假设有这么一个类:
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 }
请你实现一个有四个线程的多线程版 FizzBuzz, 同一个 FizzBuzz 实例会被如下四个线程使用:
提示:
本题已经提供了打印字符串的相关方法,如 printFizz() 等,具体方法名请参考答题模板中的注释部分。
class FizzBuzz { private int n; private static CyclicBarrier barrier = new CyclicBarrier(4); 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){ printFizz.run(); } try{ barrier.await(); } catch (BrokenBarrierException e) { e.printStackTrace(); } } } // printBuzz.run() outputs "buzz". public void buzz(Runnable printBuzz) throws InterruptedException { for(int i = 1 ; i <= n; i++ ){ if(i % 3 != 0 && i % 5 == 0){ printBuzz.run(); } try{ barrier.await(); } catch (BrokenBarrierException e) { e.printStackTrace(); } } } // printFizzBuzz.run() outputs "fizzbuzz". public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException { for(int i = 1 ; i <= n; i++ ){ if(i % 3 == 0 && i % 5 == 0){ printFizzBuzz.run(); } try{ barrier.await(); } catch (BrokenBarrierException e) { e.printStackTrace(); } } } // 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 % 3 != 0 && i % 5 != 0){ printNumber.accept(i); } try{ barrier.await(); } catch (BrokenBarrierException e) { e.printStackTrace(); } } } }
利用CyclicBarrier类,该类基于ReentrantLock+condition原理实现,推荐学习文章CyclicBarrier学习文章
思路讲解: