java版的生产者消费者模型
2016-04-09 16:28
489 查看
package com.qing.java8; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; /** * @author liuchangqing * @time 2016年4月9日下午2:18:02 * @function 4个生产者线程,1个消费者线程 * A生产者 1 * B 2 * C 3 * D 4 * 且只能顺序生产,12341234,消费者顺序消费 * 数据存放到数组products[13]中 * 每个生产200次 */ public class CTest { private ReentrantLock lock = new ReentrantLock(true); private Condition condition = lock.newCondition(); private int products[] = new int[13]; private int serverCount = 4; // 生产者个数 private int eachProSum = 200; // 每个生产者生产总数 public static void main(String[] args) throws Exception { CTest main = new CTest(); main.run(); } void run() throws Exception { Executor executor = Executors.newFixedThreadPool(5); executor.execute(new Client()); executor.execute(new Server(1)); executor.execute(new Server(2)); executor.execute(new Server(3)); executor.execute(new Server(4)); } private int getPos = 0; // 用于记录目前读取的位置 class Server implements Runnable { private int count = 0; private int putPos; private int n; public Server(int n) { this.n = n; this.putPos = n-1; } @Override public void run() { while(true) { try { lock.lock(); while(products[putPos % products.length] != 0 || putPos - getPos >= products.length) { condition.await(); } products[putPos % products.length] = n; putPos +=serverCount; count ++; } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } finally { lock.unlock(); if(count >= eachProSum) { System.out.println("server "+n+" is done"); return; } } } } } class Client implements Runnable { @Override public void run() { while(true) { if(products[getPos % products.length] == 0) continue; try { lock.lock(); System.out.print(products[getPos % products.length]+", "); products[getPos % products.length] =0; getPos ++; condition.signalAll(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } finally { lock.unlock(); if(getPos >= eachProSum*serverCount) { System.out.println("client is done"); return; } } } } } }
借鉴disruptor的思想,序号递增。
相关文章推荐
- JAVA泛型中的类型擦除及为什么不支持泛型数组
- java学习系列----反射
- 【SVN】修改MyEclipse中的SVN地址
- 20145236 《Java程序设计》 第6周学习总结
- eclipse最有用快捷键整理
- 针对中科院java接口的使用方法和问题
- 比较字符串是否相等
- Java基础
- java--连接数据库--mysql--介绍
- java 递归算法
- Struts2源码分析(二)Struts2运行流程分析
- Java中super的几种用法并与this的区别
- struts整合之 spring 对于 destroy listen等问题
- java.net.BindException: Address already in use: JVM_Bind <null>:8001解决办法
- JAVA round 和 floor的区别
- 基于Spring3 MVC实现批量导出数据成Excel文件!
- 2.1 使用eclipse4.4 搭建 maven简单结构项目。
- Java获取月度篇(一)
- Struts2文件上传与过滤
- 快速排序_java实现