简易的实现阻塞队列

在Java中有阻塞wait()和唤醒notify()方法,于是想实现一个简易的阻塞队列

当队列满时,阻塞生产方法等待消费;当队列为空时,阻塞消费队列等待生产

public class BlockQueueTest {

    int max ;
    //维护一个队列
    final Queue<Integer> queue ;
    
    BlockQueueTest(int max , Queue<Integer> queue){
        this.max = max;
        this.queue = queue;
    }

    public void put(int i) throws InterruptedException {
        //加锁保证线程安全
        synchronized (queue){
            while (queue.size() == max) {
                System.out.println("生产队列满,阻塞生产线程");
                queue.wait();
            }
            queue.add(i);
            System.out.println("生产信息:"+i);
            //队列有数据唤醒消费
            queue.notifyAll();
        }
    }

    public void pop() throws InterruptedException {
        synchronized (queue){
            while (queue.isEmpty()) {
                System.out.println("消费队列为空,阻塞消费线程");
                queue.wait();
            }
            Integer poll = queue.poll();
            System.out.println("消费信息:"+poll);
            //队列消费了唤醒生产
            queue.notifyAll();
        }
    }

    public static void main(String[] args) {
        //设置长度只有2的队列,方便查看阻塞的情况
        int max = 2;
        Queue<Integer> queue = new ArrayDeque<>(max);
        BlockQueueTest test = new BlockQueueTest(max , queue);

        Thread product = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    test.put(i);
                    Thread.sleep(100);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        });

        Thread consumer = new Thread(() -> {
            try {
                while (true){
                    test.pop();
                    Thread.sleep(200);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        });

        product.start();
        consumer.start();
    }
}

因为用queue为对象锁,生产和消费为互斥操作,所以这种实现是最简单的实现

ArrayBlockingQueue是使用ReentrantLockCondition来实现锁和阻塞还有唤醒的

posted @ 2023-06-26 14:24  阿弱  阅读(9)  评论(0编辑  收藏  举报