我正在学习如何在 java 中使用 countdownLatch,并在代码中创建了一个简单的示例,如下所示。
我对这种机制的了解是,它只是一种强制只有一个线程等待其他线程直到他们完成工作,然后等待的线程将在其他线程完成时启动它的工作.
我的问题是,如果我有 4 个线程“t1、t2、t3 和 t4”,它们应该按照说明的顺序开始,并且每个线程应该在前一个/前一个线程完成时开始。换句话说,t2 应该等待 t1 并在 t1 结束时开始,t3 应该等待 t2 并在 t2 结束时开始,t4 应该等待 t3 并在 t3 结束时开始。
1-如何使用 CountDownLatch 和循环障碍来做到这一点?
2-传递给CountDownLatch类的构造函数的countDown参数应该代表等待的线程数吗?
代码:
public class MainClass {
public static void main(String[] args) {
CountDownLatch latch1 = new CountDownLatch(1);
Thread t1 = new Thread(new AscendingOrder(latch1));
Thread t2 = new Thread(new DescendingOrder(latch1));
t1.start();
t2.start();
}
static class AscendingOrder implements Runnable {
private CountDownLatch latch;
public AscendingOrder(CountDownLatch latch) {
// TODO Auto-generated constructor stub
this.latch = latch;
}
public void run() {
// TODO Auto-generated method stub
System.out.println("thread t1 started.");
for (int i = 0; i < 10; i++)
System.out.println(i);
this.latch.countDown();
}
}
static class DescendingOrder implements Runnable {
private CountDownLatch latch;
public DescendingOrder(CountDownLatch latch1) {
// TODO Auto-generated constructor stub
this.latch = latch1;
}
public void run() {
// TODO Auto-generated method stub
System.out.println("thread t2 started and waiting");
try {
this.latch.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 10; i > 0; i--)
System.out.println(i);
}
}
}