package com.kaka.thread;
//测试生产者消费者问题2--->信号灯法:标志位
public class TestPC2 {
public static void main(String[] args) {
TV tv=new TV();
new Actor(tv).start();
new Watcher(tv).start();
}
}
//生产者-演员
class Actor extends Thread{
TV tv=new TV();
public Actor(TV tv){
this.tv=tv;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
//每两个小时演员开始表演录制
if(i%2==0){
this.tv.act("快乐大本营");
}else{
this.tv.act("广告");
}
}
}
}
//消费者-观众
class Watcher extends Thread{
TV tv=new TV();
public Watcher(TV tv){
this.tv=tv;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
this.tv.watch();
}
}
}
//产品-节目
class TV{
String voice;
boolean flag=true;//演员表演录制时:true;观众观看时:false
//演员表演录制
public synchronized void act(String voice){
if(!flag){
try {
this.wait();//当flag为false时,观众正在观看,演员不能表演录制活动,因此等待,释放锁
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("演员表演了:"+voice);
//通知观众观看
this.notifyAll();//通知唤醒
this.voice=voice;
this.flag=!this.flag;
}
//观众观看
public synchronized void watch(){
if(flag){
try {
this.wait();//flag为真时,演员正在录制表演,因此观众无法观看,需要等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观众观看了:"+voice);
//通知演员表演
this.notifyAll();
this.flag=!this.flag;
}
}