题目
题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/fizz-buzz-multithreaded
- 编写一个可以从 1 到 n 输出代表这个数字的字符串的程序,但是:
如果这个数字可以被 3 整除,输出 "fizz"。
如果这个数字可以被 5 整除,输出 "buzz"。
如果这个数字可以同时被 3 和 5 整除,输出 "fizzbuzz"。
思路
- volatile+(锁)synchronized
- 原子类
代码
原子类
import java.util.concurrent.atomic.AtomicInteger; class Test3 { private int n; AtomicInteger atomicInteger = new AtomicInteger(1); public Test3(int n){ this.n = n; } // printFizz.run() outputs "fizz". public void fizz() throws InterruptedException{ while (atomicInteger.get() <= n) { int k = atomicInteger.get(); if(k % 3 == 0 && k % 5 != 0 && k <= n){ System.out.println("fizz"); atomicInteger.incrementAndGet(); } } } // printBuzz.run() outputs "buzz". public void buzz() throws InterruptedException{ while (atomicInteger.get() <= n) { int k = atomicInteger.get(); if(k % 3 != 0 && k % 5 == 0 && k <= n){ System.out.println("buzz"); atomicInteger.incrementAndGet(); } } } // printFizzBuzz.run() outputs "fizzbuzz". public void fizzbuzz() throws InterruptedException{ while (atomicInteger.get() <= n) { int k = atomicInteger.get(); if(k % 3 == 0 && k % 5 == 0 && k <= n){ System.out.println("fizzbuzz"); atomicInteger.incrementAndGet(); } } } // printNumber.accept(x) outputs "x", where x is an integer. public void number() throws InterruptedException{ while (atomicInteger.get() <= n) { int k = atomicInteger.get(); if(k % 3 != 0 && k % 5 != 0 && k <= n){ System.out.println(k); atomicInteger.incrementAndGet(); } } } public static void main(String[] args) throws InterruptedException{ Test3 test3 = new Test3(15); Thread thread1 = new Thread(() -> { try { test3.number(); } catch (InterruptedException e) { e.printStackTrace(); } }); Thread thread2 = new Thread(() -> { try { test3.fizz(); } catch (InterruptedException e) { e.printStackTrace(); } }); Thread thread3 = new Thread(() -> { try { test3.buzz(); } catch (InterruptedException e) { e.printStackTrace(); } }); Thread thread4 = new Thread(() -> { try { test3.fizzbuzz(); } catch (InterruptedException e) { e.printStackTrace(); } }); thread1.start(); thread2.start(); thread3.start(); thread4.start(); thread1.join(); thread2.join(); thread3.join(); thread4.join(); } }