线程轮循打印ABC...
1 package com.java.concurrent; 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 * 使用多线程的方式进行轮循打印ABCABC 9 * @author fliay 10 * 11 */ 12 public class TestABCAlternate { 13 14 public static void main(String[] args) { 15 final AlternateDemo ad = new AlternateDemo(); 16 new Thread(new Runnable() { 17 18 public void run() { 19 for(int i = 1;i<10;i++){ 20 try { 21 ad.loopA(i); 22 } catch (InterruptedException e) { 23 // TODO Auto-generated catch block 24 e.printStackTrace(); 25 } 26 } 27 } 28 },"线程1").start(); 29 30 new Thread(new Runnable() { 31 32 public void run() { 33 for(int i = 1;i<10;i++){ 34 try { 35 ad.loopB(i); 36 } catch (InterruptedException e) { 37 // TODO Auto-generated catch block 38 e.printStackTrace(); 39 } 40 } 41 } 42 },"线程2").start(); 43 44 45 new Thread(new Runnable() { 46 47 public void run() { 48 for(int i = 1;i<10;i++){ 49 try { 50 ad.loopC(i); 51 } catch (InterruptedException e) { 52 // TODO Auto-generated catch block 53 e.printStackTrace(); 54 } 55 } 56 } 57 },"线程3").start(); 58 59 60 61 } 62 63 64 65 } 66 67 68 class AlternateDemo{ 69 70 private int number=1;//当前正在执行的线程标记 71 72 private Lock lock = new ReentrantLock(); 73 74 private Condition condition1 = lock.newCondition(); 75 private Condition condition2 = lock.newCondition(); 76 private Condition condition3 = lock.newCondition(); 77 78 public void loopA(int totalLoop) throws InterruptedException{ 79 lock.lock(); 80 try{ 81 //1.判断 82 if(number!=1){ 83 condition1.await(); 84 } 85 //2.打印 86 System.out.println(Thread.currentThread().getName()+":A"+"-"+totalLoop); 87 88 //3.唤醒 89 number=2; 90 condition2.signal(); 91 }finally{ 92 lock.unlock(); 93 } 94 } 95 96 public void loopB(int totalLoop) throws InterruptedException{ 97 lock.lock(); 98 try{ 99 //1.判断 100 if(number!=2){ 101 condition2.await(); 102 } 103 //2.打印 104 System.out.println(Thread.currentThread().getName()+":B"+"-"+totalLoop); 105 106 //3.唤醒 107 number=3; 108 condition3.signal(); 109 }finally{ 110 lock.unlock(); 111 } 112 } 113 114 115 public void loopC(int totalLoop) throws InterruptedException{ 116 lock.lock(); 117 try{ 118 //1.判断 119 if(number!=3){ 120 condition3.await(); 121 } 122 //2.打印 123 System.out.println(Thread.currentThread().getName()+":C"+"-"+totalLoop); 124 125 //3.唤醒 126 number=1; 127 condition1.signal(); 128 }finally{ 129 lock.unlock(); 130 } 131 } 132 133 134 135 136 137 138 139 140 141 142 143 144 }