Condition ReentrantLock实现循环10次打印ABC方式2

import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class B { public Lock lock = new ReentrantLock(); public Condition condition1 = lock.newCondition(); public Condition condition2 = lock.newCondition(); public Condition condition3 = lock.newCondition(); public volatile int state1 = 0; public static void main(String[] args) { new B().printABC(); }public void printABC() { new Thread(new Runnable() { @Override public void run() { for (int i=0; i<10; i++) { try { lock.lock(); while (state1 != 0) { condition1.await(); } System.out.println("1--A"); state1=1; condition2.signal(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } } }).start(); new Thread(new Runnable() { @Override public void run() { for (int i=0; i<10; i++) { try { lock.lock(); while(state1 != 1) { condition2.await(); } System.out.println("2--B"); state1 = 2; condition3.signal(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } }}).start(); new Thread(new Runnable() { @Override public void run() { for (int i=0; i<10; i++) { try { lock.lock(); while(state1 != 2) { condition3.await(); } System.out.println("3--C"); state1 = 0; condition1.signal(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } }}).start(); } }

打印结果:
【Condition ReentrantLock实现循环10次打印ABC方式2】1--A
2--B
3--C
1--A
2--B
3--C
1--A
2--B
3--C
1--A
2--B
3--C
1--A
2--B
3--C
1--A
2--B
3--C
1--A
2--B
3--C
1--A
2--B
3--C
1--A
2--B
3--C
1--A
2--B
3--C

    推荐阅读