public class TestPCLight {
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++) {
if (0==i%2){
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();
}
}
}
//产品--》节目
class TV{
String voice;//表演的节目
boolean flag=true;
// 表演
public synchronized void play(String voice){
while (!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("演员表演"+voice);
//通知观众可以看表演了
this.notify();//唤醒
this.voice=voice;//演完的视频给观众
this.flag=!this.flag;
}
//观看
public synchronized void watch(){
while (flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观看了"+voice);
//通知演员表演
this.notify();
this.flag=!flag;
}
}
Java的生产者消费者的信号灯(标志位)实现
最新推荐文章于 2022-10-26 22:44:40 发布
本文通过一个Java实现的生产者消费者模式示例,展示了如何使用synchronized关键字和wait/notify方法来解决多线程之间的同步问题。演员(生产者)表演节目,观众(消费者)观看节目,两者通过一个共享的TV类进行交互。
2018

被折叠的 条评论
为什么被折叠?



