使用Semaphore 信号量实现,获取用semphore.acquire()消费一个使用许可,release()创建一个消费许可
package com.atguigu.springboot; import java.util.concurrent.Semaphore; public class ThreeThread { private static Semaphore semaphoreA = new Semaphore(1); private static Semaphore semaphoreB = new Semaphore(0); private static Semaphore semaphoreC = new Semaphore(0); static class printDemo{ public void printA(){ print('A', semaphoreA, semaphoreB); } public void printB(){ print('B', semaphoreB, semaphoreC); } public void printC(){ print('C',semaphoreC, semaphoreA); } private void print(char name, Semaphore semaphore, Semaphore nextSemphore) { for (int i = 0;i < 10; i++){ try { semaphore.acquire(); System.out.println(name + " i:" + i); nextSemphore.release(); } catch (InterruptedException e) { e.printStackTrace(); } } } } public static void main(String[] args) { final printDemo printDemo = new printDemo(); new Thread(){ @Override public void run(){ printDemo.printA(); } }.start(); new Thread(){ @Override public void run(){ printDemo.printB(); } }.start(); new Thread(){ @Override public void run(){ printDemo.printC(); } }.start(); } }