5. 阻塞队列解决生产者与消费者问题

有三个组成部分:缓冲区、生产者、消费者

生产者负责往缓冲区添加数据,消费者负责往缓冲区消耗数据,如何保证运行的时候使得生产者在缓冲区满时不添加数据,消费者在缓存空时不消费数据,这样的一个问题,就是生产者消费者问题

Demo 代码实现

使用阻塞队列实现:

生产者:

class Producer extends Thread {
    BlockingQueue<String> buffer;

    public Producer(BlockingQueue<String> buffer) {
        this.buffer = buffer;
    }

    @Override
    public void run() {
        try {
            this.buffer.put("product");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Producer is producing...");
    }
}

消费者:

class Consumer extends Thread {
    BlockingQueue<String> buffer;

    public Consumer(BlockingQueue<String> buffer) {
        this.buffer = buffer;
    }

    @Override
    public void run() {
        try {
            this.buffer.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Consumer is consuming...");
    }
}

Demo 测试:

class ProducerConsumerDemo {
    public static void main(String[] args) {
        BlockingQueue<String> buffer = new ArrayBlockingQueue<>(5);
        for (int i = 0; i < 6; i++) {
            new Producer(buffer).start();
        }
        for (int i = 0; i < 8; i++) {
            new Consumer(buffer).start();
        }
        for (int i = 0; i < 2; i++) {
            new Producer(buffer).start();
        }
    }
}

结果:

Producer is producing...
Producer is producing...
Producer is producing...
Producer is producing...
Producer is producing...
Producer is producing...
Consumer is consuming...
Consumer is consuming...
Consumer is consuming...
Consumer is consuming...
Consumer is consuming...
Consumer is consuming...
Producer is producing...
Consumer is consuming...
Producer is producing...
Consumer is consuming...

可以看见,虽然生产者在并***况下会出现不同步的情况,但缓冲区的结果严格符合两个问题的要求

全部评论

相关推荐

牛客339922477号:都不用reverse,直接-1。一行。啥送分题
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务