package JUC;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;/*** 題目:多線程之間按順序調用,實現A->B->C三個線程啟動,需求如下:* AA打印5次,BB打印10次,CC打印15次* 緊接著* AA打印5次,BB打印10次,CC打印15次* 。。。* 。。。* 。。。* 來10輪*/classShareResource{//資源類privateint number =1;//AA就是1,BB就是2,CC就是3private Lock lock =newReentrantLock();private Condition c1 = lock.newCondition();private Condition c2 = lock.newCondition();private Condition c3 = lock.newCondition();//1.判斷publicvoidprint5(){lock.lock();try{//1.判斷while(number!=1){c1.await();}//2.干活for(int i =1; i <=5; i++){System.out.println(Thread.currentThread().getName()+"\t"+ i);}//3.通知number =2;c2.signal();}catch(Exception e){e.printStackTrace();}finally{lock.unlock();}}publicvoidprint10(){lock.lock();try{//1.判斷while(number!=2){c2.await();}//2.干活for(int i =1; i <=10; i++){System.out.println(Thread.currentThread().getName()+"\t"+ i);}//3.通知number =3;c3.signal();}catch(Exception e){e.printStackTrace();}finally{lock.unlock();}}publicvoidprint15(){lock.lock();try{//1.判斷while(number!=3){c3.await();}//2.干活for(int i =1; i <=15; i++){System.out.println(Thread.currentThread().getName()+"\t"+ i);}//3.通知number =1;c1.signal();}catch(Exception e){e.printStackTrace();}finally{lock.unlock();}}}publicclassSyncAndReentrantLockDemo{publicstaticvoidmain(String []args){ShareResource shareResource =newShareResource();newThread(()->{for(int i =1; i <10; i++){shareResource.print5();}},"AA").start();newThread(()->{for(int i =1; i <10; i++){shareResource.print10();}},"BB").start();newThread(()->{for(int i =1; i <10; i++){shareResource.print15();}},"CC").start();}}
結果:只截取了一輪
AA 1
AA 2
AA 3
AA 4
AA 5
BB 1
BB 2
BB 3
BB 4
BB 5
BB 6
BB 7
BB 8
BB 9
BB 10
CC 1
CC 2
CC 3
CC 4
CC 5
CC 6
CC 7
CC 8
CC 9
CC 10
CC 11
CC 12
CC 13
CC 14
CC 15