生产者消费者

package pc;

public class Cusumer implements Runnable
{
	SyncStack stack;
	
	public Cusumer(SyncStack stack)
	{
		
		this.stack = stack;
	}

	public void run()
	{
		for(int i=0;i<20;i++)
		{
			char c=stack.pop();
		}
		try
		{
			Thread.sleep((int) (Math.random()*800));
		} 
		catch (InterruptedException e)
		{


			e.printStackTrace();
		}
	}

}

 

package pc;
public class Produced implements Runnable
{
	SyncStack stack;
	
	public Produced(SyncStack stack)
	{
		
		this.stack = stack;
	}

	public void run()
	{
		for(int i=0;i<20;i++)
		{
			char c=(char)(Math.random()*26+'A');
			stack.push(c);
		}
		try
		{
			Thread.sleep((int) (Math.random()*300));
		} 
		catch (InterruptedException e)
		{
			
			e.printStackTrace();
		}
	}

}

 

package pc;
public class SyncStack
{
	private int index=0;
	private char [] data=new char[6];//存放数据的容器
	//生产数据
	public synchronized void push(char c)
	{
		while(index==data.length)//当容器data装满了
		{
			try
			{
				this.wait();//让当先线程出于等待状态
			}
			catch (InterruptedException e)
			{
				
				e.printStackTrace();
			}
		}
		this.notify();//解除调用notify当前对象的锁定
		data[index]=c;//继续生产数据
		index++;
		System.out.println("Produced:"+c);//打印生产的数据
		
	}
	//消费数据
	public synchronized char pop()
	{
		while(index==0)//如果消费完了
		{
			try
			{
				this.wait();//让当先消费的线程出于等待状态
			} 
			catch (InterruptedException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		this.notify();//唤醒消费的线程
		index--;//继续消费
		System.out.println("消费:"+data[index]);//打印消费的产品
		return data[index];//返回消费的对象
	}
}

 

package pc;

public class SyncTest
{

	public static void main(String[] args)
	{
		SyncStack stack=new SyncStack();
		Runnable p=new Produced(stack);
		Runnable c=new Cusumer(stack);
		Thread t1=new Thread(p);
		Thread t2=new Thread(c);
		t1.start();
		t2.start();
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值