多线程 生产者消费者模式(信号灯法)

/**
 * 协作模式:生产者消费者实现方式一:信号灯法
 * 借助标志位
 * 
 * @author 14988
 *
 */
public class 多线程cooperatio信号灯法 {

	public static void main(String[] args) {
		Tv tv = new Tv();
		new Thread(new Player(tv)).start();
		new Thread(new Watcher(tv)).start();
	}

}
//生产者 演员
class Player implements Runnable {
	Tv tv;
	public Player(Tv tv) {
		this.tv = tv;
	}
	@Override
	public void run() {
		for(int i = 0;i<20;i++) {
			if(i%2 == 0) {
				this.tv.play(i+":奇葩说");
			}else {
				this.tv.play(i+":呜呜呜呜");
			}
		}
	}
	
}
//消费者 观众
class Watcher implements Runnable {
	Tv tv;
	public Watcher(Tv tv) {
		this.tv = tv;
	}
	@Override
	public void run() {
		for(int i = 0;i<20;i++) {
			tv.watch();
		}
	}
	
}
//同一个资源 电视
class Tv {
	String voice;
	//信号灯
	//T表示演员表演 观众等待
	//F表示观众观看 演员等待
	boolean flag = true;
	//表演
	public synchronized void play(String voice) {
		//演员等待
		if(!flag) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println("表演了:"+voice);
		this.voice = voice;
		//表演
		this.notifyAll();
		//切换标志
		this.flag = !this.flag;
	}
	//观看
	public synchronized void watch() {
		//观众等待
		if(flag) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println("听到了:"+voice);
		//观看
		this.notifyAll();
		//切换标志
		this.flag = !this.flag;
	}
}

 

你可能感兴趣的:(多线程 生产者消费者模式(信号灯法))