当前位置:网站首页>使用三个线程,按顺序打印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
边栏推荐
猜你喜欢

Detailed explanation of MATLAB drawing function fplot

4.发布帖子,评论帖子

泰伯效应.

Detailed introduction to the hierarchical method of binary tree creation

4. Publish Posts, Comment on Posts

5.事务管理

深入理解Mysql索引底层数据结构与算法

Doubled and sparse tables

2.登录退出,登录状态检查,验证码

Introduction to MATLAB drawing functions ezplot explanation
随机推荐
3. User upload avatar
Problems related to prime numbers - small notes
Detailed explanation of Golang garbage collection mechanism
unity Domain Reload & scene Reload 静态变量重置
测试用例练习
EastWave应用:光场与石墨烯和特异介质相互作用的研究
STM32LL library use - SPI communication
Debug on pure method is called
Unity插件-NGUI
MMD->Unity一站式解决方案
Codeforces Round #624 (Div. 3)
Doubled and sparse tables
couldn't find 'libflutter.so' --flutter
Qt | 实现一个简单的可以转动的仪表盘
Detailed introduction to the hierarchical method of binary tree creation
Based on the matrix calculation in the linear regression equation of the coefficient estimates
第二十六章:二维数组
泰伯效应.
implement tcp bbr on ns3 (在ns3上实现TCP BBR)
第二十九章:树的基本概念和性质