多線程協(xié)作--信號燈法

//信號燈法 建立標(biāo)志位
public class Exercise2 {
? ?public static void main(String[] args) {
? ? ? ?TvShow tvShow = new TvShow();
? ? ? ?new Play(tvShow).start();
? ? ? ?new Watcher(tvShow).start();
? ?}
}
//播放
class Play extends Thread{
? ?TvShow tvShow;
? ?public Play(TvShow tvShow) {
? ? ? ?this.tvShow = tvShow;
? ?}
? ?@Override
? ?public void run() {
? ? ? ?for (int i = 0; i < 20; i++) {
? ? ? ? ? ?if (i%2==0)
? ? ? ? ? ?{
? ? ? ? ? ? ? tvShow.Play("工作細(xì)胞");
? ? ? ? ? ?}
? ? ? ? ? ?else {
? ? ? ? ? ? ? ?tvShow.Play("紫羅蘭花園");
? ? ? ? ? ?}
? ? ? ?}
? ?}
}
//觀眾
class Watcher extends Thread{
? ?TvShow tvShow;
? ?public Watcher(TvShow tvShow) {
? ? ? ?this.tvShow = tvShow;
? ?}
? ?@Override
? ?public void run() {
? ? ? ?for (int i = 0; i < 20; i++) {
? ? ? ? ? ?tvShow.Watch();
? ? ? ?}
? ?}
}
//節(jié)目
class TvShow{
? ?String program;
? ?boolean flag=true;
? ?public synchronized void Play(String program)
? ?{
? ? ? ?if (!flag)
? ? ? ?{
? ? ? ? ? ?try {
? ? ? ? ? ? ? ?this.wait();
? ? ? ? ? ?} catch (InterruptedException e) {
? ? ? ? ? ? ? ?e.printStackTrace();
? ? ? ? ? ?}
? ? ? ?}
? ? ? ?System.out.println("播放了:"+program);
? ? ? ?this.notifyAll();
? ? ? ?this.program=program;
? ? ? ?this.flag=!this.flag;
? ?}
? ?public synchronized void Watch()
? ?{
? ? ? ?if (flag)
? ? ? ?{
? ? ? ? ? ?try {
? ? ? ? ? ? ? ?this.wait();
? ? ? ? ? ?} catch (InterruptedException e) {
? ? ? ? ? ? ? ?e.printStackTrace();
? ? ? ? ? ?}
? ? ? ?}
? ? ? ? ? ?System.out.println("觀看了:"+program);
? ? ? ? ? ?this.notifyAll();
? ? ? ? ? ?this.flag=!this.flag;
? ?}
}