三个线程顺序打印ABC五次:
package com.jintao.example.lock.orderprintstr;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author jinjueYang
* @description 顺序打印五次ABC
* @date 2019/11/18 9:02
*/
public class OrderPrintStr {public static void main(String[] args) throws InterruptedException {
ReentrantLock reentrantLock = new ReentrantLock();
Condition conditionA = reentrantLock.newCondition();
Condition conditionB = reentrantLock.newCondition();
Condition conditionC = reentrantLock.newCondition();
new Thread(new PrintTask(reentrantLock, conditionA, conditionB, "A")).start();
Thread.sleep(100);
new Thread(new PrintTask(reentrantLock, conditionB, conditionC, "B")).start();
Thread.sleep(100);
new Thread(new PrintTask(reentrantLock, conditionC, conditionA, "C")).start();
}static class PrintTask implements Runnable {
//打印次数
private static final int PRINT_COUNT = 5;
private ReentrantLock reentrantLock;
private Condition condition;
private Condition nextCondition;
private String printStr;
public PrintTask(ReentrantLock reentrantLock, Condition condition, Condition nextCondition, String printStr) {
this.reentrantLock = reentrantLock;
this.condition = condition;
this.nextCondition = nextCondition;
this.printStr = printStr;
} @Override
public void run() {
reentrantLock.lock();
try {
for (int i = 0;
i < PRINT_COUNT;
i++) {
System.out.print(printStr);
//唤醒下一个线程打印
this.nextCondition.signal();
if (i < PRINT_COUNT - 1) {
//最后一次打印,无需等待,不然后续没有唤醒会死锁在这里
try {
this.condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} finally {
reentrantLock.unlock();
}
}
}
}
运行结果:
【三个线程顺序打印ABC多次】ABCABCABCABCABC
推荐阅读
- 人工智能|干货!人体姿态估计与运动预测
- 分析COMP122 The Caesar Cipher
- 技术|为参加2021年蓝桥杯Java软件开发大学B组细心整理常见基础知识、搜索和常用算法解析例题(持续更新...)
- C语言学习(bit)|16.C语言进阶——深度剖析数据在内存中的存储
- Python机器学习基础与进阶|Python机器学习--集成学习算法--XGBoost算法
- 数据结构与算法|【算法】力扣第 266场周赛
- 数据结构和算法|LeetCode 的正确使用方式
- leetcode|今天开始记录自己的力扣之路
- 人工智能|【机器学习】深度盘点(详细介绍 Python 中的 7 种交叉验证方法!)
- 网络|简单聊聊压缩网络