java 生產者消費者問題

 
package wo;

public class Ex {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		common comm=new common();
		producer pr1=new producer(comm);
		producer pr2=new producer(comm);
		consumer con=new consumer(comm);
		pr1.start();
		pr2.start();
		con.start();
	}
}

class common{
	private int production[];
	private int count;
	private int BUFFERSIZE=6;
	public common()
	{
		production=new int[BUFFERSIZE];
		count=0;
	}
	public synchronized int get()
	{
		int result;
		while(count<=0)
			try
		   {
			   wait();
		   }catch(InterruptedException e){}
		result=production[--count];
		notifyAll();
		return result;
	}
	public synchronized void put(int newproduct)
	{
		while(count>=BUFFERSIZE)
			try{
				wait();
			}catch(InterruptedException e){}
			production[count++]=newproduct;
			notifyAll();
	}
}

class consumer extends Thread{
	private common comm;
	public consumer(common thiscomm)
	{
		comm=thiscomm;
	}
	public void run()
	{
		int i,production;
		for(i=0;i<20;i++)
		{
			production=comm.get();
			System.out.println("得到的數據是:"+production);
		}
		try{
			this.sleep(10);
		}catch(InterruptedException e){}
	}
}

class producer extends Thread{
	private common comm;
	public producer(common thiscomm)
	{
		comm=thiscomm;
	}
	public void run()
	{
		int i;
		for(i=0;i<10;i++)
		{
			comm.put(i);
			System.out.println("生產的數據是:"+i);
		}
		try{
			this.sleep(10);
		}catch(InterruptedException e){}
	}
}

發佈了36 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章