当前位置:网站首页>使用三个线程,按顺序打印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
边栏推荐
猜你喜欢
随机推荐
Optisystem应用:光电检测器灵敏度建模
Masters and Masters
STM32LL library - USART interrupt to receive variable length information
Open the door of electricity "Circuit" (1): voltage, current, reference direction
2.登录退出,登录状态检查,验证码
implement tcp bbr on ns3 (在ns3上实现TCP BBR)
灵活的区域定义
剑指offer:反转链表
十天学习Unity3D脚本(一)九个回调
mininet multihomed topology
Unity Line-Renderer
Based on the matrix calculation in the linear regression equation of the coefficient estimates
px和em和rem的区别
企业的电子签名、私钥签名
Qt | 读取文件内容并删除文件 QFile
光栅区域衍射级数和效率的规范
数学工具-desmos 图形曲线
golang内存相关文章-收集
Happy, 9/28 scene collection
Unity-Ads广告插件









