线程演示生产者和消费者的一个例子
来源:互联网 发布:戴蜜蜡的好处知乎 编辑:程序博客网 时间:2024/05/18 19:19
生产者:向仓库容器container中填充对象,直到达到设置的库存上限MAX,然后就wait等待,并且通知叫醒notify消费者去消费。
生产者代码:
- import java.util.List;
- public class Product implements Runnable {
- private List container = null;
- private int count;
- public Product(List lst) {
- this.container = lst;
- }
- public void run() {
- while (true) {
- synchronized (container) {
- if (container.size() > MultiThread.MAX) {
- try {
- container.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- container.add(new Object());
- container.notify();
- System.out.println("我生产了" + (++count) + "个");
- }
- }
- }
- }
消费者:消费仓库container中的货物,当库存为空等于0时就停止等待wait并且通知叫醒notify生产者。
消费者代码:
- import java.util.List;
- public class Consume implements Runnable {
- private List container = null;
- private int count;
- public Consume(List lst) {
- this.container = lst;
- }
- public void run() {
- while (true) {
- synchronized (container) {
- if (container.size() == 0) {
- try {
- container.wait();// 放弃锁
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- container.remove(0);
- container.notify();
- System.out.println("我吃了" + (++count) + "个");
- }
- }
- }
- }
运行演示:启动了一个生产者和一个消费者,可以从控制台看到生产和消费的情况。
代码:
- import java.util.ArrayList;
- import java.util.List;
- public class MultiThread {
- private List container = new ArrayList();
- public final static int MAX = 5;
- public static void main(String args[]) {
- MultiThread m = new MultiThread();
- new Thread(new Consume(m.getContainer())).start();
- new Thread(new Product(m.getContainer())).start();
- }
- public List getContainer() {
- return container;
- }
- public void setContainer(List container) {
- this.container = container;
- }
- }
- 线程演示生产者和消费者的一个例子
- Java_线程—经典的例子:生产者和消费者
- 生产者和消费者。举一个寄信的例子
- 一个简单的生产者/消费者例子
- linux线程,生产者消费者例子
- Java多线程生产者和消费者的例子
- 生产者和消费者的简单例子
- 线程中的生产者和消费者的模拟
- 线程同步:生产者和消费者的问题
- 关于线程生产者和消费者的问题
- 进程线程的生产者和消费者问题
- Java线程安全总结(包含生产者和消费者例子)
- 学习和理解JAVA线程同步--生产者与消费者例子
- 学习和理解JAVA线程同步--生产者与消费者例子
- 生产者线程和消费者线程
- java实现线程同步一个生产者和一个消费者
- 多线程生产者和消费者例子
- 一个生产者与消费者模型的多线程例子程序
- 哈哈 我来也
- 喜欢CSDN
- GDI+(矩阵,可用于做投票)
- 第一篇笔记
- u-boot源码配置原理分析
- 线程演示生产者和消费者的一个例子
- 今天学习android中sqlite自找麻烦
- 《编程之美》——强烈推荐给需要学习深入编程的人
- 第一篇日志,为了那个5分!
- 第一篇日志,为了那个5分!
- 第一篇日志,为了那个5分!
- 心态
- 窘困
- 新手体会