当前位置:网站首页>使用三个线程,按顺序打印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
边栏推荐
- 富文本编辑
- 光栅区域衍射级数和效率的规范
- MATLAB drawing command fimplicit detailed introduction to drawing implicit function graphics
- Detailed introduction to the hierarchical method of binary tree creation
- Based on the least squares linear regression equation coefficient estimation
- 软件测试基础知识(背)
- implement tcp bbr on ns3 (在ns3上实现TCP BBR)
- shader入门精要1
- 泰伯效应的建模
- 开源一个golang写的游戏服务器框架
猜你喜欢
随机推荐
EastWave应用:光场与石墨烯和特异介质相互作用的研究
第三十三章:图的基本概念与性质
泰伯效应的建模
二叉排序树与 set、map
unity 和C# 一些官方优化资料
lua编程
Unity-3D数学
UnityAPI-Ray-Physics
STM32LL library - USART interrupt to receive variable length information
饥荒联机版Mod开发——配置代码环境(二)
剑指offer:在O(1)时间删除链表结点
第三十二章:二叉树的存储与遍历
pygame image rotate continuously
change the available bandwidth of tcp flow dynamically in mininet
How does ns3 solve cross reference issue
6.统一记录日志
Evaluate multipath BBR congestion control on ns3
许多代码……
Problems related to prime numbers - small notes
第二十九章:树的基本概念和性质









