Java 实现简单的阻塞队列

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_20960159/article/details/81099650
package com.souche.car_dealer;

import java.lang.invoke.LambdaConversionException;

/**
 * @author: shichao
 * @date: 2018/7/18
 * @description: 自实现阻塞队列
 */
public class MyBlockQueue {
    private Object[] array;
    private int head;
    private int tail;
    private int maxSize;
    private int size;

    /**
     * 锁对象
     *
     * @lock
     */
    private final Object lock = new Object();

    public MyBlockQueue() {
    }

    public MyBlockQueue(int maxSize) {
        this.head = 0;
        this.tail = 0;
        this.maxSize = maxSize;
        this.array = new Object[maxSize];
    }

    public void add(Object object) throws InterruptedException {
        synchronized (lock) {
            if(array.length == size) {
                System.out.println("队列已满。。。。。。");
                lock.wait();
            }
            if (tail != array.length - 1) {
                array[++tail] = object;
            } else {
                array[0] = object;
                tail = 0;
            }
            System.out.println("向队列新增。。。。。。"+object);

            size++;
            lock.notify();
        }
    }

    public Object pop() throws InterruptedException {
        synchronized (lock) {
            if (size == 0) {
                System.out.println("队列为空。。。。。。");
                lock.wait();
            }
            Object value = array[head];
            if (head != 0) {
                head--;
            } else {
                head = array.length - 1;
            }
            System.out.println("从队列弹出。。。。。。"+value);
            size--;
            lock.notify();//达到了唤醒offer方法的条件
            return value;
        }
    }

    public static void main(String[] args) {
        final MyBlockQueue blockedQueue = new MyBlockQueue(2);
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                    blockedQueue.pop();
                    Thread.sleep(3000);
                    blockedQueue.pop();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    blockedQueue.add(1);
                    System.out.println("insert 1");
                    blockedQueue.add(2);
                    System.out.println("insert 2");
                    blockedQueue.add(3);
                    System.out.println("insert 3");
                    blockedQueue.add(4);
                    System.out.println("insert 4");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
}

猜你喜欢

转载自blog.csdn.net/qq_20960159/article/details/81099650