当前位置: 首页 > news >正文

学习笔记-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);
        }
    }
}
 

 

 2. 使用 `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);
        }
    }
}
 

 3. 使用 `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);
        }
    }
}

 

 4. 使用 `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`:通过资源计数管理同步,需注意线程安全。

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

相关文章:

  • C++基础学习
  • 【Golang学习之旅】Go-zero + Gen:如何使用 Gen 提升 Go 开发效率
  • AI学习资料留档(持续更新)
  • windows下适用msvc编译ffmpeg 适用于ffmpeg-7.1
  • 解释 Node.js 的事件循环机制,理解微任务(microtask)与宏任务(macrotask)的区别?
  • Qt监控系统远程回放/录像文件远程下载/录像文件打上水印/批量多线程极速下载
  • JVM 面试
  • 【Linux】文件系统深度解析:从基础到高级应用
  • unity学习59: 滑动条 和 滚动条 滚动区域
  • additional-spring-configuration-metadata.json实现springboot自定义提示
  • python 视频网站爬虫教程,爬虫入门教程(付安装包)
  • Java语言基础 标识符、变量
  • 泛微Ecode新增Button调用服务器中的JSP页面里的方法
  • RabbitMQ系列(五)基本概念之Queue
  • MySQL 中如何解决深度分页的问题? MySQL中 join、inner join、left join、right join区别
  • 解决 ERROR 1130 (HY000): Host is not allowed to connect to this MySQL server
  • springboot、deepseek4j、bge-m3和milvus
  • 关于“你对 Spring Cloud 的理解”详细讲解?
  • bean的管理-03.第三方bean
  • 第8章:流式海啸:数据重构
  • 国内景观设计公司前十名/seo查询友情链接
  • 做牛津纺衬衫的网站/关键字排名查询工具
  • 做网站为什么先交定金/企业网站优化解决方案
  • 成都住建局官网查房源/厦门网站seo
  • C 如何做简易网站/5月新冠病毒最新消息
  • 建设委员会网站首页/seo实战密码第三版pdf