zoom 算法面试题多线程打印abcd

259 阅读1分钟

实现三个线程 A、B、C 依次打印 a、b、c 并循环 100 次

使用 wait() 和 notifyAll() 方法来控制线程的执行顺序

/**
 * @Author: andy
 * @Date: 2024/7/8 19:36
 * @Description:
 **/
public class ABCPrinter {

    private int count; // 打印次数
    private int state; // 当前状态

    public ABCPrinter(int count){
        this.count =count;
        this.state =0;
    }

    public synchronized void printA() throws InterruptedException {
        for (int i = 0; i < count; i++) {
            while (state % 3 != 0){ //0 不是A打印的轮次就等待
                wait();
            }
            System.out.println("a");
            state++;
            notifyAll();
        }
    }
    public synchronized void printB() throws InterruptedException {
        for (int i = 0; i < count; i++) {
            while (state % 3 !=1){ // 1 不是A打印的轮次就等待
                wait();
            }
            System.out.println("b");
            state++;
            notifyAll();
        }
    }

    public synchronized void printC() throws InterruptedException {
        for (int i = 0; i < count; i++) {
            while (state % 3 !=2){ // 2 不是A打印的轮次就等待
                wait();
            }
            System.out.println("c");
            state++;
            notifyAll();
        }
    }

    public static void main(String[] args) {
        ABCPrinter printer = new ABCPrinter(100);

        new Thread(() ->{
            try {
                printer.printA();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        },"A").start();

        new Thread(() ->{
            try {
                printer.printB();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        },"B").start();

        new Thread(() ->{
            try {
                printer.printC();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        },"C").start();
    }
}