Java程序之多线程顺序打印 ABC--Condition(推荐)
package abc3; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; class ABCPrinter {//使用ReentrantLock + condition //这里指的是三个线程总共打印100个 private static final int PRINT_COUNT = 15; private static volatile int count = 0;//静态保证类的所有对象都共享一份 volatile保证可见性,禁止指令重排序 private static final Lock lock = new ReentrantLock(); private static final Condition conditionA = lock.newCondition(); private static final Condition conditionB = lock.newCondition(); private static final Condition conditionC = lock.newCondition(); public static void main(String[] args) { new Thread(() -> println("a", conditionA, conditionB)).start(); new Thread(() -> println("b", conditionB, conditionC)).start(); new Thread(() -> println("c", conditionC, conditionA)).start(); } private static void println(String str, Condition current, Condition next) { try { lock.lock(); while (count < PRINT_COUNT) { while (count % 3 != getThreadIndex(str)) {//套while循环 防止虚假唤醒 current.await(); } if (count < PRINT_COUNT) {//双重判断 防止最后阻塞的线程唤醒后 打印数字超过范围 System.out.println(Thread.currentThread().getName() + " : " + count + " : " + str); } count++; next.signal(); } } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } private static int getThreadIndex(String str) { switch (str) { case "a": return 0; case "b": return 1; case "c": return 2; default: throw new IllegalArgumentException("Invalid thread name"); } } }