【多线程】交替输出abc

package com.xf;

public class WaitNotify {
    // 等待标记
    private int flag;
    // 循环次数
    private final int loopNumber;

    public WaitNotify(int flag, int loopNumber) {
        this.flag = flag;
        this.loopNumber = loopNumber;
    }

    // 打印
    public void print(String str, int waitFlag, int nextFlag) {
        for (int i = 0; i < loopNumber; i++) {
            synchronized (this) {
                // 未获得锁
                while (flag != waitFlag) {
                    try {
                        this.wait(); // 进入等待
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                // 获得了锁
                System.out.print(str);
                flag = nextFlag; // 等待标记改为下一个标记
                this.notifyAll(); // 唤醒所有线程, 再与等待标记对比
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}
package com.xf;

public class aaa {

    public static void main(String[] args) {
        WaitNotify wn = new WaitNotify(1, 500);// 首先把等待标记设为1, 循环次数设为5次
        new Thread(() -> {
            wn.print("a", 1, 2); // a的等待标记是1, 下一个标记是2
        }).start();
        new Thread(() -> {
            wn.print("b", 2, 3); // b的等待标记是2, 下一个标记是3
        }).start();
        new Thread(() -> {
            wn.print("c", 3, 1); // c的等待标记是3, 下一个标记是1
        }).start();
    }
}

 

posted @ 2022-08-31 15:21  wujf  阅读(22)  评论(0编辑  收藏  举报