信号灯模式实现
package com.lzs.utils;class Test1 { public static void main(String[] args) { Movie movie=new Movie(); Player player=new Player(movie); Watcher watcher=new Watcher(movie); Thread t1=new Thread(player); Thread t2=new Thread(watcher); t1.start(); t2.start(); }}class Player implements Runnable{ private Movie movie; public Player(Movie movie){ this.movie=movie; } @Override public void run() { for (int i=0;i<20;i++){ if(0==i%2){ movie.play("疯狂动物城"); }else { movie.play("呵呵"); } } }}class Watcher implements Runnable{ private Movie movie; public Watcher(Movie movie){ this.movie=movie; } @Override public void run() { for (int i=0;i<20;i++){ movie.watch(); } }}class Movie{ private String pic; /* *信号灯 *flag=true 生产者生产,消费者等待 *flag=true 生产者等待,消费者消费 */ private boolean flag=true; public synchronized void play(String pic){ if(!flag){//product wait try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } //product start try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } //product finished this.pic=pic; //tell to consum this.notify(); //product stop this.flag=false; } public synchronized void watch() { if(flag){//consumer wait try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } //consumer start try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } //consumer finished System.out.println(pic); //tell to product this.notify(); //consume stop this.flag=true; }}