Java多线程-信号灯模式

多线程信号的玩法


public class SignTest {
    public static void main(String[] args) {
        Drama drama = new Drama();
        new Thread(new Actor(drama)).start();
        new Thread(new Audience(drama)).start();
    }
}

class Actor extends Thread {
    Drama drama;

    public Actor(Drama drama) {
        this.drama = drama;
    }

    @Override
    public void run() {
        int n = 1;
        for (int i = 0; i < 30; i++) {
            if (i % 3 == 0) {
                this.drama.playDrama("West Word S" + n++);
            } else {
                this.drama.playDrama("Ads time");
            }
        }
    }
}

class Audience extends Thread {

    Drama drama;

    public Audience(Drama drama) {
        this.drama = drama;
    }

    @Override
    public void run() {
        for (int i = 0; i < 30; i++) {
            drama.watchDrama();
        }
    }
}

class Drama {
    String name;
    boolean flag = true;

    public synchronized void playDrama(String name) {
        if (!flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Actor play " + name);
        this.notify();
        this.name = name;
        this.flag = !this.flag;
    }

    public synchronized void watchDrama() {
        if (flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Audience watch " + name);
        this.notify();
        this.flag = !this.flag;
    }
}

posted @ 2021-01-02 12:35  Hlooc  阅读(107)  评论(0编辑  收藏  举报