使用多线程交替打印t1t2:
package com.lizhenxin.java0422.b3; import lombok.extern.java.Log; import lombok.extern.slf4j.Slf4j; /** * @author lizhenxin * @create 2022-04-25-23:34 */ @Slf4j public class Wait1 { static boolean isLock = false; public static void main(String[] args) { Thread t1 = new Thread(() -> { while (true){ synchronized (Wait1.class){ while (!isLock){ try { Wait1.class.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } isLock = false; Wait1.class.notify(); log.debug("t1"); } } }, "t1"); Thread t2 = new Thread(() -> { while (true){ synchronized (Wait1.class){ while (isLock){ try { Wait1.class.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } isLock = true; Wait1.class.notify(); log.debug("t2"); } } }, "t2"); t1.start(); t2.start(); } }