把flag改成一个Integer即可
/**
* @author huangke
* @date 2021/7/14 11:33
*
* 3个Condition队列交替打印
*/
public class JiaoTiShuziZimu4 {
static volatile Integer count = 0;
public static void main(String[] args) {
ReentrantLock lock = new ReentrantLock();
Condition conditionT1 = lock.newCondition();
Condition conditionT2 = lock.newCondition();
Condition conditionT3 = lock.newCondition();
Thread t1 = new Thread(() -> {
try {
lock.lock();
count++;
for (int i = 1; i <= 26; i++) {
System.out.println('a');
// 叫醒t2
conditionT2.signal();
// 加入t1并wait()
conditionT1.await();
}
conditionT2.signal();
System.out.println("队列1结束运行");
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
});
Thread t2 = new Thread(() -> {
try {
lock.lock();
if (count != 1){
// 加入t2并wait()
conditionT2.await();
}
count++;
for (int i = 1; i <= 26; i++) {
System.out.println((char)('b'));
// 叫醒t3
conditionT3.signal();
// 加入t2并wait()
conditionT2.await();
}
conditionT3.signal();
System.out.println("队列2结束运行");
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
});
Thread t3 = new Thread(() -> {
try {
lock.lock();
if (count != 2){
// 加入t3并wait()
conditionT3.await();
}
for (int i = 1; i <= 26; i++) {
System.out.println((char)('c'));
// 叫醒t1
conditionT1.signal();
// 加入t3并wait()
conditionT3.await();
}
conditionT1.signal();
System.out.println("队列3结束运行");
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
});
t3.start();
t2.start();
t1.start();
}
}