生成者消费者问题

自己实践的

/**
*
*	生成者消费者问题
**/
public class ThreadDemo{
	public static void main(String args[])
	{	
		BufferData bd  = new BufferData();
		Producer pro = new Producer(bd,"填装者1");
		Producer pro2 = new Producer(bd,"填装者2");
		Producer pro3 = new Producer(bd,"填装者3");
		Consumer con = new Consumer(bd);

		new Thread(pro).start();
		new Thread(pro2).start();
		new Thread(pro3).start();
		new Thread(con).start();
	}


}


//生产者
class Producer implements Runnable{

	private BufferData bd;
	private String name;
	public Producer(BufferData bd,String name)
	{
		this.bd  = bd;
		this.name = name;
	}
	public void run()
	{		
		int count = 10000;
		while(count >0){
			bd.setData(1, name);
			
			count--;	
		}
	}
}
//消费者
class Consumer implements Runnable
{
	private BufferData bd;
	public Consumer(BufferData bd){
		this.bd = bd;
	}
	public void run()
	{
		
		int count = 10000;
		while (count>0)
		{		
			bd.getData(1, "");
			//System.out.println(bd.toString());
			count--;
			//bd.notifyAll();	
		}
	}
}

class   BufferData{
	private  int id = 0;
	private  String name="";
	private boolean isFull = false;	
	//填装子弹
	public synchronized void setData(int n, String name)
	{
		try
		{
			if (isFull)
			{
				this.wait();		
			}
			this.id += n;
			this.name = name;
			
			if(this.id == 50){ isFull = true; this.notifyAll();}
			System.out.println(this.name+":"+"装子弹------------"+this.id+",isFull="+isFull);
			Thread.sleep(500);
	}
		catch (Exception e)
		{
			e.printStackTrace();
		}		
	}
	//打枪
	public synchronized void getData(int n, String name)
	{

		try
		{
			if (!isFull)
			{
				//System.out.println("正在填装......");
				this.wait();			
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		id = id-n;
		if(id<=0)
		{ 
			this.isFull = false;
			this.notifyAll();
		}
		System.out.println("剩余子弹------------"+id+",isFull="+isFull);	
	}

	public String toString(){
		return "id=" + id + " name=" + name;
	}
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值