生产者消费者示例一

/*
需求:
	单生产单消费
思路:
	一个线程用来生产,一个线程用来消费
步骤:
	1. 创建资源对象
	2. 创建线程任务
	3. 创建一个生产线程,一个消费线程
	4. 开启线程
*/

/*
描述资源
*/
class Resource
{
	private String name;
	private int num = 1;
	private boolean flag = false;

	/*
	生产
	*/
	public synchronized void set(String name)
	{
		if(flag)
		{
			try
			{
				wait();	
			}
			catch (InterruptedException e)
			{

			}
		}
		this.name = name + num;
		System.out.println(Thread.currentThread().getName()+"......生产......"+this.name);
		num++;
		System.out.println("num =" + num);
		flag = true;
		notify();
	}

	/*
	消费
	*/
	public synchronized void out()
	{
		if(!flag)
		{
			try
			{
				wait();	
			}
			catch (InterruptedException e)
			{

			}
		}
		System.out.println("------"+ Thread.currentThread().getName()+"......消费......" + this.name);
		num--;
		flag = false;
		notify();
	}
}

/*
生产者
*/
class Producer implements Runnable
{
	private Resource r;

	public Producer(Resource r)
	{
		this.r = r;	
	}

	public void run()
	{
		while(true)
		{
			r.set("烤鸭");
		}
	}
}
/*
消费者
*/
class Consumer implements Runnable
{
	private Resource r;

	public Consumer(Resource r)
	{
		this.r = r;	
	}

	public void run()
	{
		while(true)
		{
			r.out();
		}
	}
}

class ProducerConsumer 
{
	public static void main(String[] args) 
	{
		Resource r = new Resource();
		Producer pro_runnable = new Producer(r);
		Consumer con_runnable = new Consumer(r);
		Thread pro_thread = new Thread(pro_runnable);
		Thread con_thread = new Thread(con_runnable);

		pro_thread.start();
		con_thread.start();
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值