1. 程式人生 > 實用技巧 >生產消費者模型---標誌法

生產消費者模型---標誌法

生產者消費者模型——標誌法

package Thread;
//測試生產者消費者問題2:訊號燈發,標誌位解決
public class PC2Thread {
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){
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++) {
tv.watch();
}
}
}

//產品——》節目
class TV{
//演員表演,觀眾等待 T
//觀眾觀看,演員等待 F
String voice;//表演的節目
boolean flag = true;
//表演
public synchronized void play(String voice){
if (!flag){
try {
this.wait();
} 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();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("觀看了:"+voice);
//通知演員表演
this.notifyAll();
this.flag = !this.flag;
}
}