学习笔记-07生产者-消费者模型4种实现方式

在Java中,生产者-消费者模型可以通过多种方式实现。以下是常见的几种实现方法及其代码示例:

  1. **使用 `wait()` 和 `notify()`(基础同步机制)

通过 `synchronized` 块和 `Object` 的等待/唤醒机制实现。

public class WaitNotifyExample {

private final Queue<Integer> queue = new LinkedList<>();

private final int MAX_SIZE = 10;

public void produce() throws InterruptedException {

while (true) {

synchronized (queue) {

while (queue.size() == MAX_SIZE) {

queue.wait(); // 队列满时等待

}

int value = new Random().nextInt(100);

queue.add(value);

System.out.println("生产: " + value);

queue.notifyAll(); // 唤醒消费者

}

Thread.sleep(500);

}

}

public void consume() throws InterruptedException {

while (true) {

synchronized (queue) {

while (queue.isEmpty()) {

queue.wait(); // 队列空时等待

}

int value = queue.poll();

System.out.println("消费: " + value);

queue.notifyAll(); // 唤醒生产者

}

Thread.sleep(1000);

}

}

}

  1. 使用 `BlockingQueue`(线程安全队列)

直接利用 `BlockingQueue` 的阻塞特性简化代码。

import java.util.concurrent.BlockingQueue;

import java.util.concurrent.LinkedBlockingQueue;

public class BlockingQueueExample {

private final BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(10);

public void produce() throws InterruptedException {

while (true) {

int value = new Random().nextInt(100);

queue.put(value); // 队列满时自动阻塞

System.out.println("生产: " + value);

Thread.sleep(500);

}

}

public void consume() throws InterruptedException {

while (true) {

int value = queue.take(); // 队列空时自动阻塞

System.out.println("消费: " + value);

Thread.sleep(1000);

}

}

}

  1. 使用 `Lock` 和 `Condition`(更灵活的锁)

通过显式锁和条件变量实现细粒度控制。

import java.util.concurrent.locks.*;

import java.util.Queue;

import java.util.LinkedList;

public class LockConditionExample {

private final Queue<Integer> queue = new LinkedList<>();

private final int MAX_SIZE = 10;

private final Lock lock = new ReentrantLock();

private final Condition notFull = lock.newCondition();

private final Condition notEmpty = lock.newCondition();

public void produce() throws InterruptedException {

while (true) {

lock.lock();

try {

while (queue.size() == MAX_SIZE) {

notFull.await(); // 等待队列不满

}

int value = new Random().nextInt(100);

queue.add(value);

System.out.println("生产: " + value);

notEmpty.signal(); // 唤醒消费者

} finally {

lock.unlock();

}

Thread.sleep(500);

}

}

public void consume() throws InterruptedException {

while (true) {

lock.lock();

try {

while (queue.isEmpty()) {

notEmpty.await(); // 等待队列不空

}

int value = queue.poll();

System.out.println("消费: " + value);

notFull.signal(); // 唤醒生产者

} finally {

lock.unlock();

}

Thread.sleep(1000);

}

}

}

  1. 使用 `Semaphore`(信号量控制资源)

通过信号量管理可用资源数量。

import java.util.concurrent.Semaphore;

import java.util.Queue;

import java.util.LinkedList;

public class SemaphoreExample {

private final Queue<Integer> queue = new LinkedList<>();

private final int MAX_SIZE = 10;

private final Semaphore semProducer = new Semaphore(MAX_SIZE);

private final Semaphore semConsumer = new Semaphore(0);

private final Object lock = new Object();

public void produce() throws InterruptedException {

while (true) {

semProducer.acquire(); // 获取生产许可

synchronized (lock) {

int value = new Random().nextInt(100);

queue.add(value);

System.out.println("生产: " + value);

}

semConsumer.release(); // 释放消费许可

Thread.sleep(500);

}

}

public void consume() throws InterruptedException {

while (true) {

semConsumer.acquire(); // 获取消费许可

synchronized (lock) {

int value = queue.poll();

System.out.println("消费: " + value);

}

semProducer.release(); // 释放生产许可

Thread.sleep(1000);

}

}

}

总结

以上四种是Java中实现生产者-消费者的主流方式:

  1. `wait()/notify()`:适合基础场景,需手动处理同步。

  2. `BlockingQueue`:代码最简洁,推荐优先使用。

  3. `Lock` + `Condition`:提供更灵活的锁控制。

  4. `Semaphore`:通过资源计数管理同步,需注意线程安全。

根据具体需求(如性能、复杂度、可扩展性)选择合适的方式。

相关推荐
weixin_4918533142 分钟前
SpringBoot 实现 RAS+AES 自动接口解密
java·spring boot·后端
明长歌43 分钟前
【javascript】new.target 学习笔记
javascript·笔记·学习
程序员良辰3 小时前
Spring与SpringBoot:从手动挡到自动挡的Java开发进化论
java·spring boot·spring
鹦鹉0073 小时前
SpringAOP实现
java·服务器·前端·spring
练习时长两年半的程序员小胡4 小时前
JVM 性能调优实战:让系统性能 “飞” 起来的核心策略
java·jvm·性能调优·jvm调优
崎岖Qiu4 小时前
【JVM篇11】:分代回收与GC回收范围的分类详解
java·jvm·后端·面试
墨染枫5 小时前
pytorch学习笔记-自定义卷积
pytorch·笔记·学习
27669582926 小时前
东方航空 m端 wasm req res分析
java·python·node·wasm·东方航空·东航·东方航空m端
许苑向上6 小时前
Spring Boot 自动装配底层源码实现详解
java·spring boot·后端
喵叔哟6 小时前
31.【.NET8 实战--孢子记账--从单体到微服务--转向微服务】--单体转微服务--财务服务--收支分类
java·微服务·.net