生产者消费者例子-采用wait()和notify()
2016-01-19 17:40
429 查看
package com.ProductA 4000 ndConsume; public class Storage { private int maxnum; private int left; public Storage(int max){ this.maxnum = max; } public synchronized void product(int expect){ while(true){ System.out.println("start to product"); if(expect>this.maxnum){ System.out.println("The storage max is:"+this.maxnum+",you can only product that"); expect = this.maxnum; } System.out.println("thread:"+Thread.currentThread().getName()+",expect product:"+expect); if(left>=maxnum){ try { System.out.println("product wait left:"+left+",expect:"+expect); wait(); } catch (InterruptedException e) { } } left += (maxnum-left)>expect?expect:maxnum-left; System.out.println("thread:"+Thread.currentThread().getName()+",product over,left:"+left+",expect:"+expect); notifyAll(); } } public synchronized void consume(int expect){ while(true){ System.out.println("start to consume"); if(expect>this.maxnum){ System.out.println("The storage max is:"+this.maxnum+",you can only product that"); expect = this.maxnum; } System.out.println("thread:"+Thread.currentThread().getName()+",expect consume:"+expect); if(left<expect try="" system="" out="" println="" consume="" wait="" left:="" left="" expect:="" expect="" catch="" interruptedexception="" e="" todo="" auto-generated="" block="" printstacktrace="" -="(left-expect)">0?expect:left; System.out.println("thread:"+Thread.currentThread().getName()+",consume over,left:"+left+",expect:"+expect); notifyAll(); } } public static void main(String[] args){ Storage storage = new Storage(200); Producer producer1 = new Producer(storage, 10); Consumer consumer2 = new Consumer(storage, 30); Thread thread1 = new Thread(producer1); thread1.start(); Thread thread2 = new Thread(consumer2); thread2.start(); } } </expect>
package com.ProductAndConsume; public class Producer implements Runnable { private int expect; private Storage storage; public Producer(Storage storage,int expect){ this.storage = storage; this.expect = expect; } @Override public void run() { storage.product(expect); } }
package com.ProductAndConsume; public class Consumer implements Runnable { private int expect; private Storage storage; public Consumer(Storage storage,int expect){ this.storage = storage; this.expect = expect; } @Override public void run() { storage.consume(expect); } }
相关文章推荐
- JAVA生产者消费者(线程同步)代码学习示例
- Java 多线程 生产者—消费者 通用模式(synchronized已被Lock替代!)
- 多线程 等待唤醒机制 生产者消费者 (Lock jdk1.5版)
- 生产者消费者问题分析
- 生产者消费者问题之子弹上膛问题
- 2015年考研核心考点命题思路解密——操作系统 第2章 进程管理 PV算法 文件打印问题 生产者——消费者问题
- JAVA基础之多线程详解
- 并发编程--在同步代码中使用条件实现生产者消费者
- 黑马程序员---2015.6.18笔记---线程--死锁
- 生产者消费者问题(thinking in java 709 )
- 多线程+生产者、消费者问题
- java多线程之生产者消费者问题
- 黑马程序员-Thread-生产者消费者
- 使用Condition的生产者消费者模式
- 生产者-消费者模式 系列 之二 ReentrantLock, Condition 篇
- JAVA学习笔记(四十二)-生产者消费者模型
- 生产者消费者问题【线程中ConcurrentLinkedQueue】
- Linux多线程实践(5) --Posix信号量与互斥量解决生产者消费者问题
- Linux多线程实践(8) --Posix条件变量解决生产者消费者问题
- java 生产者消费者问题