代码改变世界

Java经典线程同步问题------生产者与消费者

2012-07-26 19:38  javaspring  阅读(251)  评论(0编辑  收藏  举报

先上代码

class Test
{
	public static void main(String []args)
	{
		Queue q=new Queue();
		Producer p=new Producer(q);
		Consumer c=new Consumer(q);
		p.start();
		c.start();
	}
}

class Producer extends Thread
{
	Queue q;
	Producer(Queue q)
	{
		this.q=q;
	}
	public void run()
	{
		for(int i=0;i<10;i++)
		{	
			q.put(i);
			System.out.println("Producer put"+i);
		}
	}
}
class Consumer extends Thread
{
	Queue q;
	Consumer(Queue q)
	{
		this.q=q;
	}
	public void run()
	{
		while(true)
		{
			System.out.println("Consumer get"+q.get());
		}
	}	
}

class Queue
{
	int value;
	boolean bFull=false;
	public synchronized void put(int i)
	{
		
		if(!bFull)
		{
		value=i;
		bFull=true;
		notify();
		}
	try{
	wait();
	}
	catch(Exception e)
	{}
	}
	public synchronized int get()
	{
	if(!bFull)
	{
		try
		{
			wait();
		}
		catch(Exception e)
		{
		
		}
	}
	bFull=false;
	notify();
	return value;
	}
}

运行结果

Producer put0
Consumer get0
Consumer get1
Producer put1
Consumer get2
Producer put2
Consumer get3
Producer put3
Consumer get4
Producer put4
Consumer get5
Producer put5
Consumer get6
Producer put6
Consumer get7
Producer put7
Consumer get8
Producer put8
Consumer get9
Producer put9