手写阻塞队列

        自己实现阻塞队列的话可以采用Object下的wait和notify方法,也可以使用Lock锁提供的Condition来实现,本文就是自己手撸的一个简单的阻塞队列。最近面试京东时遇到让实现阻塞队列的思路,希望本文能对大家有帮助。个人手撸如有错误还请批评指正。

public class BoundedBlockQueue {

    // 队列容器
    private LinkedList buffer;
    private int maxSize;

    private Lock lock;
    private Condition fullCondition;
    private Condition unFullCondition;

    public BoundedBlockQueue(int maxSize) {
        buffer = new LinkedList<>();
        this.maxSize = maxSize;
        lock = new ReentrantLock();
        fullCondition = lock.newCondition();
        unFullCondition = lock.newCondition();
    }

    private void put(Object obj) {
        lock.lock();
        try {
            while (buffer.size() >= maxSize) {
                System.out.println("阻塞队满了");
                fullCondition.await();
            }
        } catch (InterruptedException e) {
            fullCondition.signal();
            e.printStackTrace();
        }
        buffer.add(obj);
        unFullCondition.signal();

    }

    private Object get() {
        Object obj = null;
        lock.lock();
        try {
            while (buffer.size() ==0 ) {
                System.out.println("阻塞队空了");
                unFullCondition.await();
            }
            obj = buffer.poll();
            fullCondition.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return obj;
    }

    public static void main(String[] args) {
        BoundedBlockQueue queue2 = new BoundedBlockQueue(5);
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                queue2.put(i);
                System.out.println("塞入" + i);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread t2 = new Thread(() -> {
            for (;;) {
                System.out.println("消费"+queue2.get());
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        t2.start();
    }

}
 
  

 

手写阻塞队列_第1张图片

你可能感兴趣的:(java面试题,手写阻塞队列)