Java 多线程 生产者与消费者问题测试代码

public class ConsumerAndProducer{
	public static void main(String[] args){
			Box box=new Box();
			Producer p=new Producer(box);
			Consumer c=new Consumer(box);
			new Thread(p).start();
			new Thread(c).start();

			
	}	
}

class Food{
	int id;
	Food(int id){
		this.id=id;	
	}
	
	public String toString(){
		return "Food : " + this.id;	
	}
}

class Box{
	int index = 0;
	Food[] arrFood = new Food[6];
	
	public synchronized void put(Food food){
		while(index==arrFood.length){
			try{
				this.wait();	
			}catch(InterruptedException e){
				e.printStackTrace();
			}
		}
		this.notifyAll();
		arrFood[index++]=food;
	}
	
	public synchronized Food get(){
		while(index==0){
			try{
				this.wait();	
			}catch(InterruptedException e){
				e.printStackTrace();
			}
		}
		this.notifyAll();
		return arrFood[--index];
	}
		
}

class Producer implements Runnable{
	
	Box box=null;
	
	Producer(Box box){
		this.box=box;	
	}
	
	public void run(){
		for(int i=0;i<20;i++){
			Food food = new Food(i);
			System.out.println("Put : " + food);
			box.put(food);	
			try{
				Thread.sleep((int)(Math.random()*100));
			}catch(InterruptedException e){
				e.printStackTrace();
			}
		}
	}	
}

class Consumer implements Runnable{
	
	Box box=null;
	
	Consumer(Box box){
		this.box=box;	
	}
	
	public void run(){
		for(int i=0;i<20;i++){
			Food food=box.get();
			System.out.println("Get : " + food);
			try{
				Thread.sleep((int)(Math.random()*200));
			}catch(InterruptedException e){
				e.printStackTrace();
			}
		}
	}	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值