Java 多线程 -- 协作模型:生产消费者实现方式二:信号灯法

使用信号灯法实现生产消费者模式需要借助标志位。
下面以演员表演,观众观看电视为列,写一个demo

同一资源 电视:

//同一资源 电视
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;
	}

}

生产者 演员:

//生产者 演员
class Player extends Thread {
	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("琅琊榜");
			} else {
				this.tv.play("太火了,插播一条广告");
			}
		}
	}
}

消费者 观众:

//消费者 观众
class Watcher extends Thread {
	Tv tv;

	public Watcher(Tv tv) {
		this.tv = tv;
	}
	
	@Override
	public void run() {
		for (int i = 0; i < 20; i++) {
			this.tv.watch();
		}
	}

}

测试代码:

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

运行结果:

Java 多线程 -- 协作模型:生产消费者实现方式二:信号灯法

代码运行正常,使用信号灯法实现生产消费者模式成功。