当前位置:网站首页>使用三个线程,按顺序打印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
边栏推荐
猜你喜欢
随机推荐
动态规划理论篇
光栅区域衍射级数和效率的规范
Network Security Packet Capture
动态数组-vector
implement tcp bbr on ns3 (在ns3上实现TCP BBR)
Litestar 4D – WebCatalog 7:全自动数据管理
Codeforces Round #605 (Div. 3)
锥形相位掩模的Talbot图像
嵌入式学习硬件篇------初识ARM
泰伯效应的建模
C#高级教程
Codeforces Round #605 (Div. 3)
如何编辑VirtualLab Fusion结果的格式
MMD->Unity一站式解决方案
Qt | 实现一个简单的可以转动的仪表盘
第三十一章:二叉树的概念与性质
STM32LL library - USART interrupt to receive variable length information
Installation and configuration of Spark and related ecological components - quick recall
Redis common interview questions
C#实现简单的计算器