LeetCode(1195):交替打印字符串 Fizz Buzz Multithreaded(JUC)

2020.7.7 LeetCode 從零單刷個人筆記整理(持續更新)

github:https://github.com/ChopinXBP/LeetCode-Babel

傳送門:交替打印字符串

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 outputs fizz.

Thread B will call buzz() to check for divisibility of 5 and outputs buzz.

Thread C will call fizzbuzz() to check for divisibility of 3 and 5 and outputs fizzbuzz.

Thread D will call number() which should only output the numbers.

編寫一個可以從 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 實例會被如下四個線程使用:

線程A將調用 fizz() 來判斷是否能被 3 整除,如果可以,則輸出 fizz。

線程B將調用 buzz() 來判斷是否能被 5 整除,如果可以,則輸出 buzz。

線程C將調用 fizzbuzz() 來判斷是否同時能被 3 和 5 整除,如果可以,則輸出 fizzbuzz。

線程D將調用 number() 來實現輸出既不能被 3 整除也不能被 5 整除的數字。




package JUC;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.IntConsumer;

/**
 *
 * 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.
 * 編寫一個可以從 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。
 *
 */

public class FizzBuzzMultithreaded {
}

//ReentrantLock + AtomicInteger
//原子類用於條件判別和自增。所有線程共同爭用同一把鎖,直到每個線程打印之後就緒所有其他線程並釋放鎖,不滿足條件的線程繼續阻塞,滿足條件的線程可以打印。
class FizzBuzz {
    private int n;
    private ReentrantLock lock;
    private Condition condition;
    private AtomicInteger num;

    public FizzBuzz(int n) {
        this.n = n;
        lock = new ReentrantLock();
        condition = lock.newCondition();
        num = new AtomicInteger(1);
    }

    // printFizz.run() outputs "fizz".
    public void fizz(Runnable printFizz) throws InterruptedException {
        while(num.get() <= n){
            lock.lock();
            try{
                final int curNum = num.get();
                if(curNum % 3 == 0 && curNum % 5 != 0){
                    printFizz.run();
                    num.getAndAdd(1);
                    condition.signalAll();
                }else {
                    condition.await();
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }

    // printBuzz.run() outputs "buzz".
    public void buzz(Runnable printBuzz) throws InterruptedException {
        while(num.get() <= n){
            lock.lock();
            try{
                final int curNum = num.get();
                if(curNum % 3 != 0 && curNum % 5 == 0){
                    printBuzz.run();
                    num.getAndAdd(1);
                    condition.signalAll();
                }else{
                    condition.await();
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }

    // printFizzBuzz.run() outputs "fizzbuzz".
    public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {
        while(num.get() <= n){
            lock.lock();
            try{
                final int curNum = num.get();
                if(curNum % 3 == 0 && curNum % 5 == 0){
                    printFizzBuzz.run();
                    num.getAndAdd(1);
                    condition.signalAll();
                }else {
                    condition.await();
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void number(IntConsumer printNumber) throws InterruptedException {
        while(num.get() <= n){
            lock.lock();
            try{
                final int curNum = num.get();
                if(curNum % 3 != 0 && curNum % 5 != 0){
                    printNumber.accept(num.getAndAdd(1));
                    condition.signalAll();
                }else {
                    condition.await();
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }
}

//Semaphore
//由number線程負責控制信號量,每次打印前進行阻塞,根據當前數字釋放信號量;其餘線程打印後均釋放number線程的信號量。同時僅有一個線程在打印
class FizzBuzz2 {
    private int n;
    private Semaphore semaphoreF;
    private Semaphore semaphoreB;
    private Semaphore semaphoreFB;
    private Semaphore semaphoreN;

    public FizzBuzz2(int n) {
        this.n = n;
        semaphoreF = new Semaphore(0);
        semaphoreB = new Semaphore(0);
        semaphoreFB = new Semaphore(0);
        semaphoreN = new Semaphore(1);
    }

    // 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){
                semaphoreF.acquire();
                printFizz.run();
                semaphoreN.release();
            }
        }
    }

    // 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){
                semaphoreB.acquire();
                printBuzz.run();
                semaphoreN.release();
            }
        }
    }

    // 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){
                semaphoreFB.acquire();
                printFizzBuzz.run();
                semaphoreN.release();
            }
        }
    }

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

//CyclicBarrier
//CyclicBarrier每輪for循環等待四個線程,並同時釋放,但只有能夠打印的線程進行打印。
class FizzBuzz3 {
    private int n;
    private CyclicBarrier cyclicBarrier;

    public FizzBuzz3(int n) {
        this.n = n;
        cyclicBarrier = new CyclicBarrier(4);
    }

    // printFizz.run() outputs "fizz".
    public void fizz(Runnable printFizz) throws InterruptedException {
        for(int i = 1; i <= n; i++) {
            try{
                cyclicBarrier.await();
            }catch (BrokenBarrierException e){
                e.printStackTrace();
            }
            if(i % 3 == 0 && i % 5 != 0){
                printFizz.run();
            }
        }
    }

    // printBuzz.run() outputs "buzz".
    public void buzz(Runnable printBuzz) throws InterruptedException {
        for(int i = 1; i <= n; i++) {
            try{
                cyclicBarrier.await();
            }catch (BrokenBarrierException e){
                e.printStackTrace();
            }
            if(i % 3 != 0 && i % 5 == 0){
                printBuzz.run();
            }
        }
    }

    // printFizzBuzz.run() outputs "fizzbuzz".
    public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {
        for(int i = 1; i <= n; i++) {
            try{
                cyclicBarrier.await();
            }catch (BrokenBarrierException e){
                e.printStackTrace();
            }
            if(i % 3 == 0 && i % 5 == 0){
                printFizzBuzz.run();
            }
        }
    }

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







#Coding一小時,Copying一秒鐘。留個言點個讚唄,謝謝你#

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章