多线程循环打印abc
import java.util.concurrent.CountDownLatch;
public class PrintXYZ {
private CountDownLatch xCount = new CountDownLatch(1);
private CountDownLatch yCount = new CountDownLatch(1);
private CountDownLatch zCount = new CountDownLatch(1);
public void print() {
Thread threadA = new Thread() {
public void run() {
for (int i = 0; i < 10; i++) {
try {
xCount.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("X");
yCount.countDown(); //忘了具体方法了 应该不对
xCount = new CountDownLatch(1);
}
}
};
Thread threadB = new Thread() {
public void run() {
for (int i = 0; i < 10; i++) {
try {
yCount.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Y");
zCount.countDown(); //忘了具体方法了 应该不对
yCount = new CountDownLatch(1);
}
}
};
Thread threadC = new Thread() {
public void run() {
for (int i = 0; i < 10; i++) {
try {
zCount.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Z");
if (i < 9) {
xCount.countDown(); //忘了具体方法了 应该不对
zCount = new CountDownLatch(1);
}
}
}
};
threadC.start();
threadB.start();
threadA.start();
}
public static void main(String[] args) {
PrintXYZ printXYZ = new PrintXYZ();
printXYZ.print();
printXYZ.xCount.countDown();
}
}
如果你喜欢本文, 请长按二维码,关注公众号 分布式编程.
作者:分布式编程
出处:https://zthinker.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。