线程间通信-多生产者多消费者
2016-07-14 20:49
246 查看
class ProducerConsumerDemo { public static void main(String[] args){ Resource resource = new Resource(); //多个生产者,多个消费者 new Thread(new Producer(resource)).start(); new Thread(new Producer(resource)).start(); new Thread(new Consumer(resource)).start(); new Thread(new Consumer(resource)).start(); } } class Resource { private String name; private int count = 1; private boolean flag = false; public synchronized void set(String name){ while(flag) try{wait();}catch (Exception e){} this.name = name + "--" +count++; System.out.println(Thread.currentThread().getName()+"...生产者..."+this.name); flag = true; this.notifyAll(); } public synchronized void out(){ while(!flag) try{wait();}catch (Exception e){} System.out.println(Thread.currentThread().getName()+"...消费者..."+this.name); flag = false; this.notifyAll(); } } class Producer implements Runnable{ private Resource r; Producer(Resource r){ this.r = r; } public void run(){ while(true){ r.set("+商品+"); } } } class Consumer implements Runnable{ private Resource r; Consumer(Resource r){ this.r = r; } public void run(){ while(true){ r.out(); } } }
相关文章推荐
- JAVA生产者消费者(线程同步)代码学习示例
- Java 多线程 生产者—消费者 通用模式(synchronized已被Lock替代!)
- 多线程 等待唤醒机制 生产者消费者 (Lock jdk1.5版)
- 生产者消费者问题分析
- 生产者消费者问题之子弹上膛问题
- 2015年考研核心考点命题思路解密——操作系统 第2章 进程管理 PV算法 文件打印问题 生产者——消费者问题
- JAVA基础之多线程详解
- 并发编程--在同步代码中使用条件实现生产者消费者
- 抽空写的网站抓图片c++,增加了简单的多线程和互斥
- 黑马程序员---2015.6.18笔记---线程--死锁
- 生产者消费者例子-采用wait()和notify()
- 生产者消费者问题(thinking in java 709 )
- 多线程+生产者、消费者问题
- java多线程之生产者消费者问题
- 黑马程序员-Thread-生产者消费者
- 线程的相关知识、JAVA实现死锁、生产者消费者问题
- 生产者消费者模型(多个生产者和多个消费者)JDK1.5之前实现版
- 使用Condition的生产者消费者模式
- java多线程之生产者消费者经典问题
- 生产者-消费者模式 系列 之二 ReentrantLock, Condition 篇