Thread--使用condition实现顺序执行
1 package condition; 2 3 import java.util.concurrent.locks.Condition; 4 import java.util.concurrent.locks.ReentrantLock; 5 6 import threadLocalTest2.ThreadA; 7 8 public class Run { 9 10 private static volatile int nextPrintWho = 1; 11 private static ReentrantLock lock = new ReentrantLock(); 12 private static final Condition conditionA = lock.newCondition(); 13 private static final Condition conditionB = lock.newCondition(); 14 private static final Condition conditionC = lock.newCondition(); 15 16 public static void main(String[] args) { 17 Thread threadA = new Thread() { 18 19 @Override 20 public void run() { 21 try { 22 lock.lock(); 23 while(nextPrintWho != 1) { 24 conditionA.await(); 25 } 26 for(int i=0; i<3; i++) { 27 System.out.println("ThreadA " + (i+1)); 28 } 29 nextPrintWho = 2; 30 conditionB.signalAll(); 31 } catch (InterruptedException e) { 32 // TODO Auto-generated catch block 33 e.printStackTrace(); 34 } finally { 35 lock.unlock(); 36 } 37 } 38 39 }; 40 Thread threadB = new Thread() { 41 42 @Override 43 public void run() { 44 try { 45 lock.lock(); 46 while(nextPrintWho != 2) { 47 conditionB.await(); 48 } 49 for(int i=0; i<3; i++) { 50 System.out.println("ThreadB " + (i+1)); 51 } 52 nextPrintWho = 3; 53 conditionC.signalAll(); 54 } catch (InterruptedException e) { 55 // TODO Auto-generated catch block 56 e.printStackTrace(); 57 } finally { 58 lock.unlock(); 59 } 60 } 61 62 }; 63 Thread threadC = new Thread() { 64 65 @Override 66 public void run() { 67 try { 68 lock.lock(); 69 while(nextPrintWho != 3) { 70 conditionC.await(); 71 } 72 for(int i=0; i<3; i++) { 73 System.out.println("ThreadC " + (i+1)); 74 } 75 nextPrintWho = 1; 76 conditionA.signalAll(); 77 } catch (InterruptedException e) { 78 // TODO Auto-generated catch block 79 e.printStackTrace(); 80 } finally { 81 lock.unlock(); 82 } 83 } 84 85 }; 86 for(int i=0; i<5; i++) { 87 new Thread(threadA).start(); 88 new Thread(threadB).start(); 89 new Thread(threadC).start(); 90 } 91 } 92 93 }