Condition ReentrantLock循环10次打印ABC错误分析

错误原因就是:
Condition ReentrantLock循环10次打印ABC错误分析
文章图片

应该改为:
Condition ReentrantLock循环10次打印ABC错误分析
文章图片

输出正常:

A B C A B C A B C A B C A B C A B C A B C A B C A B C A B C

import java.awt.image.VolatileImage; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class AABBCC {static Lock lock = new ReentrantLock(); final static Condition condition1 = lock.newCondition(); final static Condition condition2 = lock.newCondition(); final static Condition condition3 = lock.newCondition(); private volatile int state = 1; public static void main(String[] args) {AABBCC aabbcc = new AABBCC(); Thread thread1 = new Thread(()->{ aabbcc.print("A",1,2,condition1,condition2); }); Thread thread2 = new Thread(()->{ aabbcc.print("B",2,3,condition2,condition3); }); Thread thread3 = new Thread(()->{ aabbcc.print("C",3,1,condition3,condition1); }); thread1.start(); thread2.start(); thread3.start(); }public void print(String s,int flg,int nextState,Condition currentCondition,Condition nextCondition){ for(int i=0; i<2; i++){ try { lock.lock(); if(flg == state){ System.out.println(s); state = nextState; nextCondition.signal(); } currentCondition.await(); }catch (Exception e){ e.printStackTrace(); }finally { lock.unlock(); } } }}

假如情况:thread1执行nextCondition.signal(); 后 thread2 thread3都已经执行完currentCondition.await();
state=1
假如外面的for循环 i<2 即循环2次:
thread1:
i=0 A signalThread2 本线程await
i=1 await A singal i=2 A singal i=3 A singal
当thread3 singal时 打印A 本线程wait

thread2:
i=0 本线程await
i=1 B singalThread3 本线程await
当thread1 singal时 打印B 本线程await

thread3:
i=0本线程await
i=1 C singalThread1 本线程await
那么打印结果是:
A
B
C
A
B
thread1 waiting
thread2 waiting
thread3 for循环进不去
所以最终结果是 线程1 线程2 死死地等待 程序结束不了
假如是非正常情况:thread1执行完nextCondition.signal(); ,thread2才开始执行if(flg == state){,thread2执行完的时候,thread3才开始执行if(flg == state){
等等情况
会打印出多种结果,但相同的是 程序都不会终止
比如以下打印结果都会出现,具体再分析原因吧,以上 只分析了2种情况:
Condition ReentrantLock循环10次打印ABC错误分析
文章图片

Condition ReentrantLock循环10次打印ABC错误分析
文章图片

【Condition ReentrantLock循环10次打印ABC错误分析】Condition ReentrantLock循环10次打印ABC错误分析
文章图片

    推荐阅读