当前位置:网站首页>使用三个线程,按顺序打印X,Y,Z,连续打印10次
使用三个线程,按顺序打印X,Y,Z,连续打印10次
2022-08-02 14:13:00 【墨、鱼】
/** * 题目描述:使用三个线程,按顺序打印X,Y,Z,连续打印10次。 * @author xujian * 2021-06-25 13:38 **/
public class PrintXYZ {
//定义CountDownLatch,起到线程通知的作用
private static CountDownLatch cd1 = new CountDownLatch(1);
private static CountDownLatch cd2 = new CountDownLatch(1);
private static CountDownLatch cd3 = new CountDownLatch(1);
public static void main(String[] args) {
Thread x = new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
//线程启动之后等待,直到cd1的门闩变为0
cd1.await();
System.out.println(Thread.currentThread().getName()+":X");
//将cd2的门闩减为0,使cd2可以从等待返回
cd2.countDown();
//新建一个CountDownLatch用于下一次循环
cd1 = new CountDownLatch(1);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
},"print-x");
Thread y = new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
cd2.await();
System.out.println(Thread.currentThread().getName()+":Y");
cd3.countDown();
cd2 = new CountDownLatch(1);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
},"print-y");
Thread z = new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
cd3.await();
System.out.println(Thread.currentThread().getName()+":Z");
System.out.println("-----------");
cd1.countDown();
cd3 = new CountDownLatch(1);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
},"print-z");
x.start();
y.start();
z.start();
//三个线程启动完都会等待各自的门闩
//cd1门闩先减为0,意味着线程print-x会先从等待中返回,从而先打印X
cd1.countDown();
}
}
效果展示
print-x:X
print-y:Y
print-z:Z
-----------
print-x:X
print-y:Y
print-z:Z
-----------
print-x:X
print-y:Y
print-z:Z
-----------
print-x:X
print-y:Y
print-z:Z
-----------
print-x:X
print-y:Y
print-z:Z
-----------
print-x:X
print-y:Y
print-z:Z
-----------
print-x:X
print-y:Y
print-z:Z
-----------
print-x:X
print-y:Y
print-z:Z
-----------
print-x:X
print-y:Y
print-z:Z
-----------
print-x:X
print-y:Y
print-z:Z
-----------
这是我自己想的办法,能实现效果。如果大家有更好的办法欢迎指导~
相关代码请参考:https://gitee.com/xujian01/blogcode/tree/master/src/main/java/thread
边栏推荐
猜你喜欢

implement tcp copa on ns3

Detailed introduction to the hierarchical method of binary tree creation

Unity-3D数学

锥形相位掩模的Talbot图像

第三十二章:二叉树的存储与遍历

剑指offer:删除链表中重复的节点

2. Log out, log in state examination, verification code

5款最好用的免费3D建模软件(附下载链接)
![[System Design and Implementation] Flink-based distracted driving prediction and data analysis system](/img/f0/23ac631b6eb9b794224d8ae78e6523.png)
[System Design and Implementation] Flink-based distracted driving prediction and data analysis system

7.Redis
随机推荐
队列与栈
动态规划理论篇
5.事务管理
Optisystem应用:光电检测器灵敏度建模
计算机导论——数据库
泰伯效应的建模
饥荒联机版Mod开发——准备工具(一)
mininet hosts talk to real internet
面试汇总
Qt | 定时器的使用 QTimer
第二十七章:时间复杂度与优化
【离散化+前缀和】Acwing802. 区间和
深入理解Mysql索引底层数据结构与算法
学习笔记(01):activiti6.0从入门到精通-工作流的介绍以及插件的安装
从FAST TCP到POWERTCP
2342. 数位和相等数对的最大和 哈希优化
锥形相位掩模的Talbot图像
饥荒联机版Mod开发——配置代码环境(二)
mininet multihomed topology
Qt | 串口通信 QSerialPort