package com.leigod.user.middle.service.impl; import lombok.SneakyThrows; /** * @author Sam.yang * @since 2021/3/29 17:58 */ public class Test { //定义锁对象 Object lock = new Object(); //定义通知对象 boolean tagA = true; boolean tagB = false; boolean tagC = false; public static void main(String[] args) { Test test = new Test(); for (int i = 0; i < 100; i++) { Thread threadA = new Thread(new Runnable() { @SneakyThrows @Override public void run() { test.printA(Thread.currentThread().getName()); } }); Thread threadB = new Thread(new Runnable() { @SneakyThrows @Override public void run() { test.printB(Thread.currentThread().getName()); } }); Thread threadC = new Thread(new Runnable() { @SneakyThrows @Override public void run() { test.printC(Thread.currentThread().getName()); } }); threadA.run(); threadB.run(); threadC.run(); } } /** * 打印A */ private void printA(String tName) throws InterruptedException { synchronized (lock) { while (!tagA) { lock.wait(); } System.out.println("A"); tagA = false; tagB = true; lock.notify(); } } /** * 打印B */ private void printB(String tName) throws InterruptedException { synchronized (lock) { while (!tagB) { lock.wait(); } System.out.println("B"); tagA = false; tagB = false; tagC = true; lock.notify(); } } /** * 打印C */ private void printC(String tName) throws InterruptedException { synchronized (lock) { while (!tagC) { lock.wait(); } System.out.println("C"); tagA = true; tagB = false; tagC = false; lock.notify(); } } }