生产者和消费者模型
来源:互联网 发布:淘宝中年女秋装新款 编辑:程序博客网 时间:2024/04/25 23:57
public class ProductAndConsumer { public static void main(String[] args) { StackBasket s = new StackBasket(); Producer p = new Producer(s); Consumer c = new Consumer(s); Thread tp = new Thread(p); Thread tc = new Thread(c); tp.start(); tc.start(); }}//class Apple { private int id; Apple(int id) { this.id = id; } public String toString() { return "Apple: " + id; }}class Producer implements Runnable { StackBasket ss = new StackBasket(); Producer(StackBasket ss) { this.ss = ss; } public void run() { int i = 0; for (;;) { Apple m = new Apple(i++); ss.push(m); try { Thread.sleep((int) (Math.random() * 500)); } catch (InterruptedException e) { e.printStackTrace(); } } }}class Consumer implements Runnable { StackBasket ss = new StackBasket(); Consumer(StackBasket ss) { this.ss = ss; } public void run() { for (;;) { Apple m = ss.pop(); try { Thread.sleep((int) (Math.random() * 1000)); } catch (InterruptedException e) { e.printStackTrace(); } } }}class StackBasket { Apple sm[] = new Apple[5]; int index = 0; public synchronized void push(Apple m) { try { while (index == sm.length) { System.out.println("!!!!!!!!!No place to apple!!!!!!!!!"); this.wait(); } this.notify(); } catch (InterruptedException e) { e.printStackTrace(); } catch (IllegalMonitorStateException e) { e.printStackTrace(); } sm[index] = m; index++; System.out.println("Product " + m + " total " + index + " apples"); } public synchronized Apple pop() { try { while (index == 0) { System.out.println("!!!!!!!!!No Apple!!!!!!!!!"); this.wait(); } this.notify(); } catch (InterruptedException e) { e.printStackTrace(); } catch (IllegalMonitorStateException e) { e.printStackTrace(); } index--; System.out.println("Consum " + sm[index] + " total " + index + " Apples"); return sm[index]; }}
0 0
- 生产者和消费者模型
- 生产者和消费者模型
- 多线程模型:生产者和消费者
- JAVA 生产者和消费者模型
- 剖析生产者和消费者模型
- 生产者消费者模型(单个生产者和单个消费者)
- 单个生产者和单个消费者模型(spsc)
- 线程之间生产者和消费者模型
- python线程和进程,生产者消费者模型
- java多线程之生产者和消费者模型
- java多线程--生产者和消费者模型
- 多线程编程之生产者和消费者模型
- 使用BlockingQueue实现生产者和消费者模型
- 例说生产者和消费者模型
- 信号量(生产者和消费者模型)
- c++11 生产者和消费者模型
- 生产者-消费者模型
- 生产者/消费者模型
- OpenGL扫描线(橡皮筋之后的工作)
- jquery中attr和prop的区别
- CSS实现垂直居中
- 十进制转化为二进制230
- OpenGL、WebGL、H5
- 生产者和消费者模型
- Hibernate监听用户操作日志
- Android四大布局之帧布局及其运用
- Failed to register in JMX: javax.naming.NamingException: Could not load resource factory class
- 如何构建第一个Spark项目代码
- Android架构合集(请关注github,后续github上面会继续更新)
- 大数据管理:数据集成的技术、方法与最佳实践 读书笔记一
- vb中几种循环
- CtreeCtrl节点展开关闭切换图标