1 import com.sun.org.apache.bcel.internal.generic.NEW; 2 3 import java.util.concurrent.locks.Condition; 4 import java.util.concurrent.locks.Lock; 5 import java.util.concurrent.locks.ReentrantLock; 6 7 /** 8 * //AA 5 BB 10 CC 15 9 * 来10轮 10 */ 11 public class SyncAndReentrantLockDemo { 12 13 public static void main(String[] args) { 14 ShareResource shareResource=new ShareResource(); 15 16 new Thread(()->{ 17 for (int i = 0; i <10 ; i++) { 18 shareResource.printAA(); 19 } 20 },"AA").start(); 21 22 new Thread(()->{ 23 for (int i = 0; i <10 ; i++) { 24 shareResource.printBB(); 25 } 26 27 },"BB").start(); 28 29 new Thread(()->{ 30 for (int i = 0; i <10 ; i++) { 31 shareResource.printCC(); 32 } 33 34 },"CC").start(); 35 36 } 37 38 } 39 class ShareResource{ 40 private int number =1; 41 Lock lock=new ReentrantLock(); 42 Condition conditionA=lock.newCondition(); 43 Condition conditionB=lock.newCondition(); 44 Condition conditionC=lock.newCondition(); 45 public void printAA(){ 46 lock.lock(); 47 try{ 48 while(number!=1){ 49 try { 50 conditionA.await(); 51 }catch (Exception e){ 52 53 } 54 } 55 for (int i = 0; i <5 ; i++) { 56 System.out.println(Thread.currentThread().getName()+"\t 打印AA"+i); 57 } 58 number=2; 59 conditionB.signal(); 60 }catch (Exception e){ 61 62 }finally { 63 lock.unlock(); 64 } 65 } 66 public void printBB(){ 67 lock.lock(); 68 try{ 69 while(number!=2){ 70 try { 71 conditionB.await(); 72 }catch (Exception e){ 73 74 } 75 } 76 for (int i = 0; i <10 ; i++) { 77 System.out.println(Thread.currentThread().getName()+"\t 打印BB"+i); 78 } 79 number=3; 80 conditionC.signal(); 81 }catch (Exception e){ 82 83 }finally { 84 lock.unlock(); 85 } 86 87 } 88 public void printCC(){ 89 lock.lock(); 90 try{ 91 while(number!=3){ 92 try { 93 conditionC.await(); 94 }catch (Exception e){ 95 96 } 97 } 98 for (int i = 0; i <15 ; i++) { 99 System.out.println(Thread.currentThread().getName()+"\t 打印CC"+i); 100 } 101 number=1; 102 conditionA.signal(); 103 }catch (Exception e){ 104 105 }finally { 106 lock.unlock(); 107 } 108 109 } 110 }