Java生产者消费者代码

/**
 * 生产者消费者例子
 * @author MrYang
 *
 */
public class Test {

	private int p = 0 ;
	
	 class Warehouse {
		
		Object[] o = null ;
		
		public Warehouse(int length){
			o = new Object[length];
		}
		
		int index = 0 ;
		
		public synchronized void addProduct(){
			if(index == o.length){
				try {
					this.wait() ;
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			o[index] = new Object() ;
			index  ++;
			this.notify() ;
			p++;
			System.out.println("生成了一个产品,剩余数量:"+p);
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		public synchronized void reduceProduct(){
				if(index== 0){
					try {
						this.wait() ;
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				index -- ;
				this.notify();
				p-- ;
				System.out.println("消费了一个产品,剩余数量:"+p);
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
		}
	}
	
	class Consumer implements Runnable{
		
		Warehouse warehouse = null ;
		
		public Consumer(Warehouse w){
			warehouse = w ;
		}
		public void run(){
			for(int i = 0 ; i < 10 ; i++){
			warehouse.reduceProduct();
			}
		}
	}
	
	class Producer implements Runnable{
		
		Warehouse warehouse = null ;
		
		public Producer(Warehouse w){
			warehouse = w ;
		}
		public void run(){
			for(int i = 0 ; i < 10 ; i++){
				warehouse.addProduct();
			}
		}
	}
	
	public void run(){
		Warehouse wa = new Warehouse(4);
		Thread c = new Thread(new Consumer(wa));
		Thread p = new Thread(new Producer(wa));
		p.start();
		c.start();
	}
	
	public static void main(String[] args){
		Test t = new Test();
		t.run();
	}
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值