信号灯法实现多线程通信

信号灯法实现多线程通信

多线程接近尾声了,学习是一方面,练习也很重要

例子:

演员表演节目

观众观看

package com.example.multi_thread;

import lombok.SneakyThrows;

// 信号灯法实现肯德基购餐
public class TestPC2 {
    public static void main(String[] args) {
        Tv tv = new Tv();
        new Thread(new Player(tv)).start();
        new Thread(new Watcher(tv)).start();
    }
}

class Player implements Runnable {
    Tv tv;

    public Player(Tv tv) {
        this.tv = tv;
    }

    @SneakyThrows
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            if (i % 2 == 0) {
                tv.show("脱口秀");
            } else {
                tv.show("吐槽");
            }

        }

    }
}


class Watcher implements Runnable {
    Tv tv;

    public Watcher(Tv tv) {
        this.tv = tv;
    }


    @SneakyThrows
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            tv.watch();
        }
    }
}

class Tv {
    boolean flag = true; // true 生产者生产, 消费者等待 false 生产者等待, 消费者消费

    String voice;

    public synchronized void show(String voice) throws InterruptedException {
        if (!flag) {
            wait();
        }
        this.voice = voice;
        System.out.println("表演了" + voice);
        notifyAll();
        flag = !flag;

    }

    public synchronized void watch() throws InterruptedException {
        if (flag) {
            wait();
        }
        System.out.println("观看了" + voice);
        notifyAll();
        flag = !flag;
    }


}

输出:

表演了脱口秀
观看了脱口秀
表演了吐槽
观看了吐槽
表演了脱口秀
观看了脱口秀
表演了吐槽
观看了吐槽
表演了脱口秀
观看了脱口秀
表演了吐槽
观看了吐槽
表演了脱口秀
观看了脱口秀
表演了吐槽
观看了吐槽
表演了脱口秀
观看了脱口秀
表演了吐槽
观看了吐槽
posted @ 2021-11-15 17:40  Oh,mydream!  阅读(39)  评论(0编辑  收藏  举报