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

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;
	}
}

 

全部评论

相关推荐

08-08 16:33
唐山学院 Java
职场水母:首先,简历太长,对于实习和应届找工作,hr一眼扫的是学历,技术看实习,你写的技术栈字太多了,尽量用一句话概括不用写那么详细,技术面的时候会问的,而且技术栈都会在实习或者项目里体现,你要做的是,把你的简历浓缩为一页,删除没用的东西,比如实践经历,自我评价,这些纯废话,没用,专业技能写的太离谱,你真的熟练掌握了吗,建议都写熟悉,找工作和写论文不一样,追求的是干练和实用,把实习经历和项目提前,把掌握的技术栈写到最后,然后去找实习,
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务