实现思路
- 创建两个
CountDownLatch
对象,分别用于控制线程 B 等待线程 A 执行完毕,以及线程 C 等待线程 B 执行完毕。
- 在线程 A 执行完毕后,调用
CountDownLatch
的 countDown()
方法,将计数减一。
- 在线程 B 的开始部分调用
CountDownLatch
的 await()
方法,等待计数变为 0,即线程 A 执行完毕。
- 在线程 B 执行完毕后,再次调用
CountDownLatch
的 countDown()
方法,将计数减一。
- 在线程 C 的开始部分调用
CountDownLatch
的 await()
方法,等待计数变为 0,即线程 B 执行完毕。
代码实现
import java.util.concurrent.CountDownLatch;
public class ThreadSequenceWithCountDownLatch {
public static void main(String[] args) {
// 创建两个CountDownLatch对象,初始计数都为1
CountDownLatch latchAB = new CountDownLatch(1);
CountDownLatch latchBC = new CountDownLatch(1);
Thread threadA = new Thread(() -> {
System.out.println("线程A开始执行");
// 模拟线程A执行任务
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程A执行完毕");
latchAB.countDown();
});
Thread threadB = new Thread(() -> {
try {
System.out.println("线程B等待线程A执行完毕");
latchAB.await();
System.out.println("线程B开始执行");
// 模拟线程B执行任务
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程B执行完毕");
latchBC.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread threadC = new Thread(() -> {
try {
System.out.println("线程C等待线程B执行完毕");
latchBC.await();
System.out.println("线程C开始执行");
// 模拟线程C执行任务
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程C执行完毕");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
threadA.start();
threadB.start();
threadC.start();
}
}