LeetCode 1195:交替打印字符串

题目描述

编写一个可以从 1 到 n 输出代表这个数字的字符串的程序,但是:

  • 如果这个数字可以被 3 整除,输出 “fizz”。
  • 如果这个数字可以被 5 整除,输出 “buzz”。
  • 如果这个数字可以同时被 3 和 5 整除,输出 “fizzbuzz”。

例如,当 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 实例会被如下四个线程使用:

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

解题思路

对于常见的并发工具类要熟练使用,CyclicBarrier、CountDownLatch、ReentrantLock 、Condition、Semaphore、Synchronized用法与区别要熟练掌握。比如CyclicBarrier计数器是可重用的,而CountDownLatch的计数器是一次性的CountDownLatch一般用于某个线程A等待若干个其他线程执行完任务之后,它才执行;而CyclicBarrier一般用于一组线程互相等待至某个状态,然后这一组线程再同时执行。

代码实现

CyclicBarrier

class FizzBuzz {
    private int n;

    private CyclicBarrier cb = 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{
                cb.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{
                cb.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{
                cb.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{
                cb.await();
            }catch(BrokenBarrierException e){
                e.printStackTrace();
            }
        }
        
    }
}

ReentrantLock + Condition

class FizzBuzz {
    private int n;
    private int i = 1;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();


    public FizzBuzz(int n) {
        this.n = n;
    }

    // printFizz.run() outputs "fizz".
    public void fizz(Runnable printFizz) throws InterruptedException {
        while(i <= n){
            lock.lock();
            try{
                if(i % 3 == 0 && i % 5 != 0){                    
                    printFizz.run();
                    i++;
                    condition.signalAll();
                }else{
                    condition.await();
                }
            }finally{
               lock.unlock();
            }
        }
    }

    // printBuzz.run() outputs "buzz".
    public void buzz(Runnable printBuzz) throws InterruptedException {
        while(i <= n){
            lock.lock();
            try{
                if(i % 3 != 0 && i % 5 == 0){                    
                    printBuzz.run();
                    i++;
                    condition.signalAll();
                }else{
                    condition.await();
                }
            }finally{
               lock.unlock();
            }
        }
    }

    // printFizzBuzz.run() outputs "fizzbuzz".
    public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {
        while(i <= n){
            lock.lock();
            try{
                if(i % 3 == 0 && i % 5 == 0){                    
                    printFizzBuzz.run();
                    i++;
                    condition.signalAll();
                }else{
                    condition.await();
                }
            }finally{
               lock.unlock();
            }
        }
    }

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void number(IntConsumer printNumber) throws InterruptedException {
        while(i <= n){
            lock.lock();
            try{
                if(i % 3 != 0 && i % 5 != 0){                    
                    printNumber.accept(i);
                    i++;
                    condition.signalAll();
                }else{
                    condition.await();
                }
            }finally{
               lock.unlock();
            }
        }
        
    }
}

ReentrantLock (Synchronized同理)

class FizzBuzz {
    private int n;
    private int i = 1;
    private Lock lock = new ReentrantLock();


    public FizzBuzz(int n) {
        this.n = n;
    }

    // printFizz.run() outputs "fizz".
    public void fizz(Runnable printFizz) throws InterruptedException {        
        while(i <= n){
            lock.lock();
            try{
                if(i <= n && i % 3 == 0 && i % 5 != 0){                    
                    printFizz.run();
                    i++;
                }                
            }finally{
                lock.unlock();
            }
        }
    }

    // printBuzz.run() outputs "buzz".
    public void buzz(Runnable printBuzz) throws InterruptedException {
        while(i <= n){
            lock.lock();
            try{
                if(i <= n && i % 3 != 0 && i % 5 == 0){                    
                    printBuzz.run();
                    i++;
                }                
            }finally{
                lock.unlock();
            }
        }
        
    }

    // printFizzBuzz.run() outputs "fizzbuzz".
    public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {
        while(i <= n){
            lock.lock();
            try{
                if(i <= n && i % 3 == 0 && i % 5 == 0){                    
                    printFizzBuzz.run();
                    i++;
                }                
            }finally{
                lock.unlock();
            }
        }
        
    }

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void number(IntConsumer printNumber) throws InterruptedException {
        while(i <= n){
            lock.lock();
            try{
                if(i <= n && i % 3 != 0 && i % 5 != 0){                    
                    printNumber.accept(i);
                    i++;
                }                
            }finally{
                lock.unlock();
            }
        }
        
    }
}

Semaphore

class FizzBuzz {
    private int i = 1;
    private int n;
    private Semaphore number = new Semaphore(1);
    private Semaphore fizz = new Semaphore(0);
    private Semaphore buzz = new Semaphore(0);
    private Semaphore fizzBuzz = new Semaphore(0);

    public FizzBuzz(int n) {
        this.n = n;
    }

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

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

    // printFizzBuzz.run() outputs "fizzbuzz".
    public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {
        while(i <= n){
            if(i <= n && i % 3 ==0 && i % 5 == 0){
                fizzBuzz.acquire();
                printFizzBuzz.run();
                i++;
                number.release();
            }
        }
        
    }

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void number(IntConsumer printNumber) throws InterruptedException {
        while(i <= n){
            number.acquire();
            if(i <= n && i % 3 !=0 && i % 5 != 0){
                printNumber.accept(i);
                i++;
                number.release();
            }else if(i <= n && i % 3 ==0 && i % 5 != 0){
                fizz.release();
            }else if(i <= n && i % 3 !=0 && i % 5 == 0){
                buzz.release();
            }else{
                fizzBuzz.release();
            }
        }
        
    }
}

总结

本题来源于Leetcode中 归属于多线程类型题目。
同许多在算法道路上不断前行的人一样,不断练习,修炼自己!
如有博客中存在的疑问或者建议,可以在下方留言一起交流,感谢各位!

觉得本博客有用的客官,可以给个赞鼓励下! 嘿嘿


版权声明:本文为weixin_43161461原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。