首页 技术 正文
技术 2022年11月9日
0 收藏 621 点赞 2,839 浏览 1024 个字

使用信号灯法实现生产消费者模式需要借助标志位。

下面以演员表演,观众观看电视为列,写一个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();}
}

运行结果:

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

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,093
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,569
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,417
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,190
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,825
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,908