Condition有序打印ABCD

【Condition有序打印ABCD】编写一个程序,开启 3个线程,这 3个线程的 ID分别为 A、 B、 C,每个线程将自己的 ID在屏幕上打印 10遍,要求输出结果必须按 ABC的顺序显示;如: ABCABC….依次递推。

import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * @author zjq * @date 2020/3/25 16:56 * * 循环打印ADC */ public class pcC { public static void main(String[] args) { Data3 data3 = new Data3(); new Thread(()->{ for(int i=0; i<10; i++){ data3.printA(); } },"A").start(); new Thread(()->{ for(int i=0; i<10; i++){ data3.printB(); } },"B").start(); new Thread(()->{ for(int i=0; i<10; i++){ data3.printC(); } },"C").start(); } } class Data3{//资源类用Lock private Lock lock = new ReentrantLock(); Condition condition1 = lock.newCondition(); Condition condition2 = lock.newCondition(); Condition condition3 = lock.newCondition(); private int num = 1; //num=1 A; num = 2 B; num =3 C public void printA(){ lock.lock(); try { //业务 while(num!=1){ condition1.await(); } System.out.println(Thread.currentThread().getName()+"=======A"); //唤醒指定的线程 num = 2; condition2.signal(); }catch (Exception e){ e.printStackTrace(); }finally { lock.unlock(); }} public void printB(){ lock.lock(); try { //业务,判断-》执行-》通知 while(num!=2){ condition2.await(); } System.out.println(Thread.currentThread().getName()+"=========B"); num = 3; condition3.signal(); }catch (Exception e){ e.printStackTrace(); }finally { lock.unlock(); } } public void printC(){ lock.lock(); try { //业务 while (num!=3){ condition3.await(); } System.out.println(Thread.currentThread().getName()+"========C"); num = 1; condition1.signal(); }catch (Exception e){ e.printStackTrace(); }finally { lock.unlock(); } }}

    推荐阅读