[設計模式]——生產者消費者模式_信號燈法

/**
 * 一個場景,共同的資源
 * 生產者消費者模式信號燈法
 * wait()等待,釋放鎖  sleep 不釋放鎖
 * notify()/notifyAll():喚醒
 * 與synchronized一起使用
 * @author Administrator
 *
 */
public class product_customer {
	private String pic;
	//信號燈  flag--->T 生產者生產,消費者等待,生產完成後通知消費
	//             F 消費者消費,生產者等待,消費完成後通知生產
	private boolean flag=true;
	/**
	 * 播放
	 */
	public synchronized void play(String pic){
		//生產者生產
		if (!flag) {
			try {
				this.wait();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		//開始生產
		try {
			Thread.sleep(600);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("生產了 "+pic);
		//生產完畢
		this.pic=pic;
		//通知消費
		this.notify();
		//生產者停下
		this.flag=false;
	}
	public synchronized void watch(){
		//消費者等待
		if (flag) {
			try {
				this.wait();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		//開始消費
		try {
			Thread.sleep(600);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("  -->消費了 "+pic);
		//消費完畢
		//通知生產
		this.notifyAll();
		//停止消費
		this.flag=true;
		
	}
}

/**
 * 生產者
 * @author Administrator
 *
 */
public class Player implements Runnable{
	product_customer m;
	public Player(product_customer m) {
		super();
		this.m = m;
	}

	@Override
	public void run() {
		for(int i=0;i<200;i++){
			if (0==i%2) {
				m.play("左青龍");
			}else {
				m.play("右白虎");
			}
		}
	}
	
}

public class Watcher implements Runnable{
	private product_customer m;
	public Watcher(product_customer m) {
		super();
		this.m = m;
	}

	@Override
	public void run() {
		for(int i=0;i<200;i++){
			m.watch();
		}
	}

}


public class App {
	public static void main(String[] args) {
		//共同的資源
		product_customer m=new product_customer();
		//多線程
		Player p=new Player(m);
		Watcher w=new Watcher(m);
		
		new Thread(p).start();
		new Thread(w).start();
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章