LeetCode 1116. 打印零与奇偶数(多线程)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_34125999/article/details/100123016

题目描述

假设有这么一个类:

class ZeroEvenOdd {
  public ZeroEvenOdd(int n) { ... }      // 构造函数
  public void zero(printNumber) { ... }  // 仅打印出 0
  public void even(printNumber) { ... }  // 仅打印出 偶数
  public void odd(printNumber) { ... }   // 仅打印出 奇数
}
相同的一个 ZeroEvenOdd 类实例将会传递给三个不同的线程:

线程 A 将调用 zero(),它只输出 0 。
线程 B 将调用 even(),它只输出偶数。
线程 C 将调用 odd(),它只输出奇数。
每个线程都有一个 printNumber 方法来输出一个整数。请修改给出的代码以输出整数序列 010203040506... ,其中序列的长度必须为 2n。

 

示例 1:

输入:n = 2
输出:"0102"
说明:三条线程异步执行,其中一个调用 zero(),另一个线程调用 even(),最后一个线程调用odd()。正确的输出为 "0102"。
示例 2:

输入:n = 5
输出:"0102030405"

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/print-zero-even-odd
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

代码及思路

import java.util.concurrent.ArrayBlockingQueue;
import java.util.function.IntConsumer;

public class ZeroEvenOdd {

    private int n;

    private Object lock = new Object();

    private ArrayBlockingQueue<Integer> zeroBlockingQueue = new ArrayBlockingQueue<>(1);

    private ArrayBlockingQueue<Integer> oddBlockingQueue = new ArrayBlockingQueue<>(1);


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

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void zero(IntConsumer printNumber) throws InterruptedException {
        for (int i = 1; i <= n; i++) {
            synchronized (lock) {
                /**
                 * zero阻塞队列,0是阻塞,1是不阻塞:
                 * 状态0:状态0是不阻塞,直接打印0,打印完毕后变成阻塞
                 * 状态1:阻塞,等待被唤醒。
                 */
                while (zeroBlockingQueue.size() == 1) {
                    lock.wait();
                }
                zeroBlockingQueue.add(1);
                printNumber.accept(0);
               // System.out.print("0");
                lock.notifyAll();
            }
        }

    }

    public void odd(IntConsumer printNumber) throws InterruptedException {
        for (int i = 1; i <= n; i++) {
            if (i % 2 != 0) {
                synchronized (lock) {
                    /**
                     * 前提:首先要打印0,如果zero不阻塞,那么就要等待
                     * odd阻塞队列,0是阻塞,1是不阻塞:
                     * 状态0:不阻塞,直接运行,运行完变成阻塞
                     * 状态1:阻塞,等待被唤醒
                     */
                    while (oddBlockingQueue.size() == 1 || zeroBlockingQueue.size() == 0) {
                        lock.wait();
                    }
                    printNumber.accept(i);
                    //System.out.print(i);
                    //清除0阻塞队列
                    zeroBlockingQueue.clear();
                    oddBlockingQueue.add(1);
                    lock.notifyAll();
                }
            }
        }
    }

    public void even(IntConsumer printNumber) throws InterruptedException {
        for (int i = 1; i <= n; i++) {
            if (i % 2 == 0) {
                synchronized (lock) {
                    /**
                     * 前提:首先要打印0,如果zero不阻塞,那么就要等待
                     * odd阻塞队列,0是阻塞,1是不阻塞:
                     * 状态0:阻塞,因为基数先打印
                     * 状态1:运行。运行完毕后清除两个阻塞队列,从新开始一轮
                     */
                    while (oddBlockingQueue.size() == 0 || zeroBlockingQueue.size() == 0) {
                        lock.wait();
                    }
                    printNumber.accept(i);
                   // System.out.print(i);
                    zeroBlockingQueue.clear();
                    oddBlockingQueue.clear();
                    lock.notifyAll();
                }
            }
        }
    }

}

测试

 public static void main(String[] args) throws InterruptedException {

        CountDownLatch countDownLatch=new CountDownLatch(1);

        ZeroEvenOdd zeroEvenOdd = new ZeroEvenOdd(5);

        Thread t1 = new Thread(() -> {
            try {
                zeroEvenOdd.zero(null);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread t2 = new Thread(() -> {
            try {
                zeroEvenOdd.even(null);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread t3 = new Thread(() -> {
            try {
                zeroEvenOdd.odd(null);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t1.start();
        t2.start();
        t3.start();
        countDownLatch.await();
    }

结果

在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_34125999/article/details/100123016
今日推荐