生产者消费者问题
来源:互联网 发布:mac本地音乐播放器 编辑:程序博客网 时间:2024/06/04 12:28
消费者生产者问题描述:有一个容器,其中生产者负责向容器中装入苹果,消费者负责从容器中取出苹果,规则要求是容器中最多能装下6个苹果,但容器中有6个苹果时,生产者再也不能向容器中加入苹果,只有当容器中的苹果数量少于6个时,才能再次添加。但容器中的苹果数量为零时,消费者不能从容器中取出,只有当容器中的苹果数量大于0时才能取出。java代码实现如下:
package com.gdut.wang;public class Apple { private int id; public Apple(int id) { super(); this.id = id; } @Override public String toString() { return "Apple [id=" + id + "]"; }}
package com.gdut.wang;public class AppleStack { private Apple[] arrApple = new Apple[6]; private int index; public synchronized Apple pop() { if (index == 0) try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } this.notify(); index--; return arrApple[index]; } public synchronized void push(Apple apple) { if (index == arrApple.length) try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } this.notify(); arrApple[index] = apple; index++; }}
package com.gdut.wang;public class Productor implements Runnable { private AppleStack as; public Productor(AppleStack as) { super(); this.as = as; } @Override public void run() { for (int i = 0; i < 20; i++) { Apple apple = new Apple(i); as.push(apple); System.out.println("放入第" + i + "个苹果"); try { Thread.sleep((int) (Math.random() * 1000)); } catch (InterruptedException e) { e.printStackTrace(); } } }}
package com.gdut.wang;public class Consumer implements Runnable { private AppleStack as; public Consumer(AppleStack as) { super(); this.as = as; } @Override public void run() { for (int i = 0; i < 20; i++) { Apple apple = as.pop(); System.out.println("拿出了第" + i + "苹果"); try { Thread.sleep((int) (Math.random() * 1000)); } catch (InterruptedException e) { e.printStackTrace(); } } }}
package com.gdut.wang;public class ProductorConsumer { private static AppleStack as = new AppleStack(); private static Consumer c = new Consumer(as); private static Productor p = new Productor(as); public static void main(String[] args) { new Thread(p).start(); new Thread(c).start(); }}
0 0
- 生产者-消费者问题
- 生产者-消费者问题
- 生产者-消费者问题
- 操作系统:生产者-消费者问题
- 生产者与消费者问题
- 生产者-消费者问题
- 关于生产者-消费者问题
- java生产者 消费者问题
- 消费者和生产者问题
- 生产者消费者问题
- 生产者消费者问题--多线程
- 生产者-消费者同步问题
- 生产者消费者问题
- 生产者与消费者问题
- 生产者 消费者问题!
- 生产者与消费者问题
- 生产者消费者问题
- 关于生产者-消费者问题
- eclipse SSE设置
- Centos 6.5 ISO 文件挂载方法
- 为什么要使用html模板技术
- 百度地图使用地理编码与反地址编码
- JSP 的九大内置对象简介
- 生产者消费者问题
- STL之priority_queue(优先队列)
- cocos2dx在C++层屏蔽emoji表情
- java入门之抽象类
- linux Redis 注册服务
- 《Java数据结构和算法(第二版)》读书笔记
- ubuntu下jdk和tomcat安装配置
- 细说JAVA反射
- 你真的了解iOS代理设计模式吗?