引入 真实快递模式下的 生产者消费者模式
消费者类
package cn.edu.Thread2;
public class Consume implements Runnable{
public int speed;
public Moniter moniter ;
public Consume() {
super();
// TODO Auto-generated constructor stub
}
public Consume(Moniter moniter , int speed) {
super();
this.speed = speed;
this.moniter = moniter;
new Thread(this,"Consume").start();
}
/**
* 消费
*/
@Override
public void run() {
while(true){
this.moniter.get(speed);
try {
Thread.sleep( (long) (Math.random()*1000));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
生存者类
package cn.edu.Thread2;
public class Produce implements Runnable {
private Moniter moniter;
private int speed;
public Produce(Moniter moniter, int speed) {
super();
this.moniter = moniter;
this.speed = speed;
new Thread(this,"Produce").start();
}
public Produce() {
super();
// TODO Auto-generated constructor stub
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
this.moniter.set(speed);
try {
Thread.sleep( (long) ( Math.random()*1000 ));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
缓冲区类
package cn.edu.Thread2;
/**
* 缓冲区
* @author Deri
*
*/
public class Moniter {
private int goods;
private final int MAX = 100;
/**
* 消费
* @param need
* @return
*/
public synchronized int get(int need){
// 当需求 大于 库存量时候。 线程等待
if(goods < need ){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
goods -= need;
System.out.println(" consume get:" + need+"\t库存量" +goods);
//唤醒其他线程
notify();
return need;
}
/**
* 生产下
* @param goods
*/
public synchronized void set(int newGood){
int count = newGood;
//如果生产达到库存 峰值 线程等待
if( (goods+newGood) > MAX){
newGood = newGood - (MAX - goods); //把 能存的先 存进来
this.goods = MAX;
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 线程等待中 消费后 唤醒 该线程 就 继续 储存
goods += newGood;
System.out.println("produce set: " + count +"\t 库存量" +goods);
notify();
}
}
测试主类
package cn.edu.Thread2;
public class TestDemo {
public static void main(String[] args) {
int proSpeed = 10;
int conSpeed = 11;
Moniter m = new Moniter();
new Produce(m, proSpeed);
new Consume(m, conSpeed);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.exit(0);
}
}
班主任强调了的多线程,今天用eclipse 做了一遍。升级了
2016年12月6日 15:31:14
mangodai