您的位置:首页 > 编程语言 > Java开发

java 实现消费者模型

2015-11-03 10:24 357 查看
// 妈妈做面包,最多20个
//大林吃面包
// 小林吃面包
// 锅里最多10个面包
<pre name="code" class="java">package TestPacage;
import java.util.Stack;
public class Brake {
public static final int MAX_NUM =10;
public static int Bread_NUM =0;
Stack<Integer> stack=new Stack<Integer>();

public synchronized void MakeBreak(Integer number){
stack.push(number);
Brake.Bread_NUM++;
}

public synchronized int EatBreak(){

Brake.Bread_NUM--;
return stack.pop();
}

}
package TestPacage;

public class Kitchen {
private Brake brake;
public static int bigLin=0;
public static int smallLin=0;
public static int Total_num=20;
public static int icount=1;

public Kitchen(Brake brake){

this.brake=brake;

}

public synchronized void make(){
if (Brake.Bread_NUM<Brake.MAX_NUM){
System.out.println(Thread.currentThread().getName()+"在做"+Kitchen.icount+"面包");
brake.MakeBreak(Kitchen.icount);
System.out.println("锅里有"+Brake.Bread_NUM+"个面包");
Kitchen.icount++;
notifyAll();

}
else{
try{
wait();
}catch(Exception e){
e.printStackTrace();
}
}

}
public synchronized void eat(){
if (Brake.Bread_NUM>0){
//System.out.println("在吃"+Kitchen.icount+"面包");
int temp=brake.EatBreak();
System.out.println(Thread.currentThread().getName()+"在吃"+temp+"面包");
System.out.println("锅里有"+Brake.Bread_NUM+"个面包");
//Kitchen.icount--;
if(Thread.currentThread().getName().equals("大林")){
bigLin++;
}else{
smallLin++;
}
notifyAll();

}
else{
try{
wait();
}catch(Exception e){
e.printStackTrace();
}
}

}

}

package TestPacage;

public class Product implements Runnable {
private Kitchen kitchen;
public Product(Kitchen kitchen){
this.kitchen=kitchen;
}
public void run(){
while(true){
if(Kitchen.icount>Kitchen.Total_num){
System.out.println(Kitchen.Total_num+"个面包已经做完");
break;
}
try{
kitchen.make();
Thread.sleep(100);

}catch(Exception e){
e.printStackTrace();
}
}
}
}

package TestPacage;

public class Consumer implements Runnable{

private Kitchen kitchen;

public Consumer(Kitchen kitchen){

this.kitchen=kitchen;
}

public void run(){
while(true){
if(Kitchen.icount>Kitchen.Total_num&& Brake.Bread_NUM<=0){
System.out.println(Kitchen.Total_num+"个面包已经吃完");
System.out.println("大林吃"+Kitchen.bigLin+"个面包");
System.out.println("小林吃"+Kitchen.smallLin+"个面包");
break;
}
try{
kitchen.eat();
Thread.sleep(1000);
}catch(Exception e){
e.printStackTrace();
}
}
}
}
package TestPacage;

public class MainTest {
public static void main(String[] args){
Brake brake= new Brake();
Kitchen kitchen =new Kitchen(brake);
Product p= new Product(kitchen);
Consumer dl = new Consumer(kitchen);
Consumer xl = new Consumer(kitchen);

Thread mother =new Thread(p,"妈妈");
Thread dalin = new Thread(dl,"大林");
Thread xiaolin = new Thread(xl,"小林");
mother.start();
dalin.start();
xiaolin.start();
try{
mother.join();
dalin.join();
xiaolin.join();

}catch(Exception e){
e.printStackTrace();
}
}

}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: