参考《Java多线程编程核心技术》
使用Condition对象可以对线程执行的业务进行排序规划
具体实现代码
1 public class Run2 { 2 private static ReentrantLock lock = new ReentrantLock(); 3 private final static Condition conditionA = lock.newCondition(); 4 private final static Condition conditionB = lock.newCondition(); 5 private final static Condition conditionC = lock.newCondition(); 6 private volatile static int nextPrintWho = 1; 7 public static void main(String[] args){ 8 Thread threadA = new Thread(){ 9 @Override 10 public void run() { 11 super.run(); 12 try { 13 lock.lock(); 14 while (nextPrintWho != 1){ 15 conditionA.await(); 16 } 17 for (int i = 0; i < 3; i++) { 18 System.out.println("ThreadA "+ (i+1)); 19 } 20 nextPrintWho = 2; 21 conditionB.signalAll(); 22 } catch (InterruptedException e) { 23 e.printStackTrace(); 24 } finally { 25 lock.unlock(); 26 } 27 } 28 }; 29 30 Thread threadB = new Thread(){ 31 @Override 32 public void run() { 33 try { 34 lock.lock(); 35 while (nextPrintWho !=2){ 36 conditionB.await(); 37 } 38 for (int i = 0; i < 3; i++) { 39 System.out.println("ThreadB "+(i+1)); 40 } 41 nextPrintWho = 3; 42 conditionC.signalAll(); 43 } catch (InterruptedException e) { 44 e.printStackTrace(); 45 } finally { 46 lock.unlock(); 47 } 48 } 49 }; 50 51 Thread threadC = new Thread(){ 52 @Override 53 public void run() { 54 try { 55 lock.lock(); 56 while (nextPrintWho != 3){ 57 conditionC.await(); 58 } 59 for (int i = 0; i < 3; i++) { 60 System.out.println("ThreadC "+(i+1)); 61 } 62 nextPrintWho = 1; 63 conditionA.signalAll(); 64 } catch (InterruptedException e) { 65 e.printStackTrace(); 66 } finally { 67 lock.unlock(); 68 } 69 } 70 }; 71 72 Thread[] aArray = new Thread[5]; 73 Thread[] bArray = new Thread[5]; 74 Thread[] cArray = new Thread[5]; 75 76 for (int i = 0; i < 5; i++) { 77 aArray[i] = new Thread(threadA); 78 bArray[i] = new Thread(threadB); 79 cArray[i] = new Thread(threadC); 80 81 aArray[i].start(); 82 bArray[i].start(); 83 cArray[i].start(); 84 } 85 } 86 }
-----------------------------------------------console---------------------------------------------------
ThreadA 1 ThreadA 2 ThreadA 3 ThreadB 1 ThreadB 2 ThreadB 3 ThreadC 1 ThreadC 2 ThreadC 3 ThreadA 1 ThreadA 2 ThreadA 3 ThreadB 1 ThreadB 2 ThreadB 3 ThreadC 1 ThreadC 2 ThreadC 3 ThreadA 1 ThreadA 2 ThreadA 3 ThreadB 1 ThreadB 2 ThreadB 3 ThreadC 1 ThreadC 2 ThreadC 3 ThreadA 1 ThreadA 2 ThreadA 3 ThreadB 1 ThreadB 2 ThreadB 3 ThreadC 1 ThreadC 2 ThreadC 3 ThreadA 1 ThreadA 2 ThreadA 3 ThreadB 1 ThreadB 2 ThreadB 3 ThreadC 1 ThreadC 2 ThreadC 3