執行緒協作-訊號燈法
阿新 • • 發佈:2022-05-27
//測試生產者消費者問題2 :訊號燈法,標誌位解決 public class Main { 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; } 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){//通過構造器,來獲取到tv this.tv=tv; }public void run(){ for(int i=0;i<20;i++){ try { tv.wait(); } catch(InterruptedException e) { System.out.println("wait"); } finally { } } } } //產品--節目 class TV{ //演員表演時,觀眾等待 true//觀眾觀看,演員等待 false String voice;//表演的節目 boolean flag=true;//預設為真 //表演 public synchronized void play(String voice){ if(!flag){//flag不等於真的時候等待 try { this.wait(); } catch(InterruptedException e) { System.out.println("wait"); } finally { } } System.out.println("演員表演了:"+voice); //通知觀眾觀看 this.notifyAll();//通知喚醒觀眾 this.voice=voice; this.flag=!this.flag; } //觀看 public synchronized void watch(){ if (flag){//如果flag等於真,那觀眾就等待 try { this.wait(); } catch(Exception e) { System.out.println("wait"); } finally { } } System.out.println("觀看了:"+voice); //通知演員表演 this.notifyAll(); this.flag=!this.flag;//取反,比如:當前flag是真的時候,就讓他為假,假則為真 } }