生产者/消费者实现方式二: 信号灯法

package com.yunding.concurrent;

/**
 * 生产者/消费者实现方式二: 信号灯法 借助标志位
 * 
 * @author beOkWithAnything
 *
 */
public class Test2 {
	public static void main(String[] args) {
		Tv tv = new Tv();
		new Player(tv).start();
		new Watcher(tv).start();
	}
}

// 演员
class Player extends Thread {
	Tv tv;

	public Player(Tv tv) {
		this.tv = tv;
	}

	@Override
	public void run() {
		for (int i = 0; i < 20; i++) {
			// 表演的节目
			this.tv.play(" " + i);
		}
	}
}

// 观众
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();
		}
	}
}

// 同一个资源:电视
class Tv {
	String voice;

	// 标志位
	boolean flag = true;

	synchronized void play(String voice) {
		// 演员等待
		if (!flag) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.voice = voice;
		System.out.println("表演了 " + voice);
		// 唤醒
		this.notifyAll();
		this.flag = !flag;
	}

	synchronized void watch() {
		// 观众等待
		if (flag) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println("听到了 " + voice);
		// 唤醒
		this.notifyAll();
		this.flag = !flag;
	}
}

 

全部评论

相关推荐

投递美团等公司10个岗位
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务