线程通信-采用标志位

发布时间 2023-03-22 21:16:18作者: 搁浅fff
package com.Java;

public class Testflag {
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 (i % 2 == 0) {
tv.play("快乐大本营");
}else {
tv.play("B站");
}
}
}
}

//消费者->观众
class Watcher extends Thread {
TV tv;

public Watcher(TV tv) {
this.tv = tv;
}

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

//产品->TV
class TV {
String voice;
boolean flag = false;

public synchronized void play(String voice) {
if (flag) {
try {
//如果还有节目则等待观众看完
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//没有节目则表演
System.out.println("演员表演了"+voice);
this.voice = voice;
this.flag = !flag;
//通知观众可以观看了
this.notifyAll();
}

public synchronized void watch() {
if (!flag) {
//如果没有节目了 就等待演员表演节目
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果有节目 则直接观看
System.out.println("观众观看了" + voice);
this.flag = !flag;
//看完通知演员开始演节目了
this.notifyAll();
}
}