多線程之間的通信生產者和消費者

package day12;
/*多線程之間的通信
 *  生產者生產 商品
 *  
 *  消費者消費商品
 * 
 *  商品有自己的 生產方法和消費方法 
 *  
 * */
public class ThreadDemo5 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//創建商品對象
		Good g=new Good();
		// 創建生產者對象
		PorduterDemo p=new PorduterDemo(g);
		 // 創建消費者對象
		ConsumerDemo c=new ConsumerDemo(g);
	   // 創建生產者線程
		new Thread(p).start();
		new Thread(p).start();
		//  創建消費者線程
		new Thread(c).start();
		new Thread(c).start();
	}
}
/*商品類 
 *   屬性  名稱 
 *        編號
 *        標記變量
 *    方法    生產的方法
 *          消費的方法
 * */
class Good 
{
	private String name;
	private int count=1;
	private boolean flag=false;
	// 生產的方法
	public synchronized void set(String name)
	{
		while(flag)
			try {
				this.wait();
			} catch (Exception e) {
				// TODO: handle exception
			}
		this.name=name+"-生產者-"+count++;
		System.out.println(Thread.currentThread().getName()+"生產者"+this.name);
		flag=true;
		this.notifyAll();
	}
	//  消費的方法
	public synchronized void out()
	{
		while(!flag)
			try {
				this.wait();
			} catch (Exception e) {
				// TODO: handle exception
			}
		System.out.println(Thread.currentThread().getName()+"消費者"+this.name);
		flag=false;
		this.notifyAll();
	}
}
//生產者  調用商品的生產方法
class PorduterDemo  implements Runnable
{
	private Good g;
	PorduterDemo(Good g)
	{
		this.g=g;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(true)
		{
			g.set("商品");
		}
	}
}
//消費者調用  商品的消費方法
class ConsumerDemo  implements Runnable
{

	private Good g;
	ConsumerDemo(Good g)
	{
		this.g=g;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(true)
		{
			g.out();
		}
	}
}


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