Condition实现多线程顺序打印:
1 import java.util.concurrent.locks.Condition; 2 import java.util.concurrent.locks.ReentrantLock; 3 4 public class Run { 5 6 volatile public static int nextPrintWho = 1; 7 private static ReentrantLock lock = new ReentrantLock(); 8 final private static Condition conditionA = lock.newCondition(); 9 final private static Condition conditionB = lock.newCondition(); 10 final private static Condition conditionC = lock.newCondition(); 11 12 public static void main(String[] args) { 13 14 Thread threadA = new Thread() { 15 @Override 16 public void run() { 17 try { 18 lock.lock(); 19 while (nextPrintWho != 1) { 20 conditionA.await(); 21 } 22 for (int i = 0; i < 3; i++) { 23 System.out.println("ThreadA " + (i+1)); 24 } 25 nextPrintWho = 2; 26 conditionB.signalAll(); 27 } catch (InterruptedException e) { 28 e.printStackTrace(); 29 }finally { 30 lock.unlock(); 31 } 32 }; 33 }; 34 Thread threadB = new Thread() { 35 @Override 36 public void run() { 37 try { 38 lock.lock(); 39 while (nextPrintWho != 2) { 40 conditionB.await(); 41 } 42 for (int i = 0; i < 3; i++) { 43 System.out.println("ThreadB " + (i+1)); 44 } 45 nextPrintWho = 3; 46 conditionC.signalAll(); 47 } catch (InterruptedException e) { 48 e.printStackTrace(); 49 }finally { 50 lock.unlock(); 51 } 52 }; 53 }; 54 Thread threadC = new Thread() { 55 @Override 56 public void run() { 57 try { 58 lock.lock(); 59 while (nextPrintWho != 3) { 60 conditionC.await(); 61 } 62 for (int i = 0; i < 3; i++) { 63 System.out.println("ThreadC " + (i+1)); 64 } 65 nextPrintWho = 1; 66 conditionA.signalAll(); 67 } catch (InterruptedException e) { 68 e.printStackTrace(); 69 }finally { 70 lock.unlock(); 71 } 72 }; 73 }; 74 Thread[] aArray = new Thread[5]; 75 Thread[] bArray = new Thread[5]; 76 Thread[] cArray = new Thread[5]; 77 for (int i = 0; i < 5; i++) { 78 aArray[i] = new Thread(threadA); 79 bArray[i] = new Thread(threadB); 80 cArray[i] = new Thread(threadC); 81 aArray[i].start(); 82 bArray[i].start(); 83 cArray[i].start(); 84 } 85 } 86 }
运行结果如下:
原文地址:https://www.cnblogs.com/wang1001/p/9579889.html
时间: 2024-10-07 22:34:57