生产者-消费者实现

package cn.gao.algorithm2.service;

/*
 * 经典的生产-消费者模式
 * 最简单的就是一个生产者和一个消费者对共同的缓冲区对象进行操作
 * 可扩展成多对多的生产者消费者模式
 */
public class Test9 {

	/**
	 * @param args
	 */
	static int common=0;
	/*box是生产消费者所操控的对象*/
	static class Box{
		public int values;/*缓冲区中的值*/
		public boolean full=false;/*表示对象缓冲区中为满的状态*/
		public synchronized int get()/*生产者调用对象*/
		{
			while(full==false)/*消费者需要等待缓冲区满才会去取其中的东西,不是满就一直等待*/
			{
				try {
					wait();/*等待生产者产生满缓冲区,唤醒此物*/
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			System.out.println("消费者消费"+values);
			full=false;
			notifyAll();
			return values;
		}
		public synchronized void put(int values)
		{
			while(full==true)/*只要缓冲区是满的,生产者就一直等待*/
			{
				try {
					wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			this.values=values;
			System.out.println("生产者生产"+values);
			full=true;
			notifyAll();
		}
	}

static class Productor extends Thread
{
	private Box box;
	
	public Productor(Box box) {
		super();
		this.box = box;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		for(int i=0;i<6;i++)
		{
			box.put(common++);
		/*
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			*/
		}
	}
	
}
static class Comsumer extends Thread
{
	private Box box;
	
	public Comsumer(Box box) {
		super();
		this.box = box;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		for(int i=0;i<6;i++)
		{
			box.get();
			/*
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			*/
		}
	}
	
}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Box box=new Box();
		Productor p1=new Productor(box);
		Productor p2=new Productor(box);
		Comsumer c1=new Comsumer(box);
		Comsumer c2=new Comsumer(box);
		p1.start();
		p2.start();
		c1.start();
		c2.start();
		

	}

}

猜你喜欢

转载自tg008007x1201205190407.iteye.com/blog/1537036