多线程--生产者和消费者
2015-07-04 15:19
330 查看
生产者-消费者问题:
生产者向产品区里放产品,当产品区里满了,需要等待;消费者从产品区里取产品消耗,当产品区里空了,需要等待。
多个生产者-多个消费者问题
由于产品区是互斥访问的,一次只有一个线程能够进入产品区,所以和上面的几乎一样,只是多加一个进程(不知道理解的是否对)
生产者向产品区里放产品,当产品区里满了,需要等待;消费者从产品区里取产品消耗,当产品区里空了,需要等待。
public class ProducerAndConsumer { //创建缓冲区 private static Buffer buffer = new Buffer(); public static void main(String[] args) { System.out.println("Hello World!"); Thread producer = new Thread(new Producer()); Thread consumer = new Thread(new Consumer()); consumer.start(); producer.start(); } //消费者 static class Consumer implements Runnable { public void run(){ try{ while(true){ buffer.poll(); Thread.sleep((int)(Math.random()*1000)); } }catch(InterruptedException ex){} } } //生产者 static class Producer implements Runnable { public void run(){ try{ while(true){ buffer.push(new Random().nextInt(20)); Thread.sleep((int)(Math.random()*1000)); } }catch(InterruptedException ex){} } } } //缓冲池 class Buffer { //创建锁 private static Lock lock = new ReentrantLock(); //条件1---缓冲池空 private static Condition empty = lock.newCondition(); //条件2---缓冲池满 private static Condition full = lock.newCondition(); //缓冲池大小 private static final int size = 10; //缓冲池 private Queue<Integer> queue = new LinkedList<Integer>(); //取数 public void poll(){ lock.lock(); try{ while(queue.size() == 0){ System.out.println("\t\t\t\tWait for producer:"); empty.await(); } int num = queue.poll(); System.out.println("\t\t\t\t["+queue.size()+"]poll:" + num); full.signal(); }catch(InterruptedException ex){ }finally{ lock.unlock(); } } //存数 public void push(int num){ lock.lock(); try{ while(queue.size() == 10){ System.out.println("Wait for consumer:"); full.await(); } queue.offer(num); System.out.println("["+queue.size()+"]push:" + num); empty.signal(); }catch(InterruptedException ex){ }finally{ lock.unlock(); } } }
多个生产者-多个消费者问题
由于产品区是互斥访问的,一次只有一个线程能够进入产品区,所以和上面的几乎一样,只是多加一个进程(不知道理解的是否对)
相关文章推荐
- Eclipse在线安装SVN
- UVA11983 - Weird Advertisement(扫描线)
- 逻辑斯特回归
- 彻底解决Ubuntu 14.04 重启后DNS配置丢失的问题
- 【视图控件篇】自定义Android控件之IOS滑动开关模拟详解
- 客户端putty, xshell连接linux中vim的小键盘问题
- response输出乱码问题
- 默认参数提升在可变参数函数的陷阱
- Objective-C(十一、不可变数组NSArray,可变数组NSMutableArray)——iOS开发基础
- grunt简记
- C++中的浅拷贝和深拷贝
- uva1339(字符串水题)
- Asp.net Vnext TagHelpers
- pycharm虚拟环境virtualnv安装MySQL扩展
- JavaSE笔记之<正则表达式>
- 《C语言及程序设计》实践参考——区号查询
- springmvc、mybatis整合数据库语句输出问题解决
- Java基础知识整理---环境变量配置
- 《C语言及程序设计》实践参考——玩转日期和时间
- mongo分片及驱动