线程交替打印

55 阅读1分钟
  1. 两个线程交替打印A、B

wait()方法会让当前线程释放锁,并进入等待状态
notify()方法会唤醒一个调用了wait()方法的线程,但是被唤醒的线程并不一定能马上执行,该线程还需要获取到锁,才能继续执行 notifyAll()可以唤醒所有调用了wait()方法的线程

public class MyThread {
    static Object lock = new Object();
    public static void main(String[] args) throws InterruptedException {
        MyThread myThread = new MyThread();
        Thread thread1 = new Thread(() -> {
            while (true) {
                synchronized (lock) {
                    lock.notifyAll();
                    System.out.println("A");
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        });
        Thread thread2 = new Thread(() -> {
            while (true) {
                synchronized (lock) {
                    lock.notifyAll();
                    System.out.println("B");
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        });
        thread1.start();
        thread2.start();
    }
}

  1. 三个线程交替打印A、B、C

juejin.cn/post/725291…