方法 1:使用 join() 方法
通过 join() 让后续线程等待前序线程完成。
java
复制代码
Thread t1 = new Thread(() -> System.out.println("T1"));
Thread t2 = new Thread(() -> {
try {
t1.join(); // 等待 T1 完成
System.out.println("T2");
} catch (InterruptedException e) { e.printStackTrace(); }
});
Thread t3 = new Thread(() -> {
try {
t2.join(); // 等待 T2 完成
System.out.println("T3");
} catch (InterruptedException e) { e.printStackTrace(); }
});
t1.start();
t2.start();
t3.start();
流程图(使用 Mermaid):
flowchart LR
T1 -->|join| T2
T2 -->|join| T3
方法 2:单线程线程池
利用 Executors.newSingleThreadExecutor() 的 FIFO 特性。
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> System.out.println("T1"));
executor.submit(() -> System.out.println("T2"));
executor.submit(() -> System.out.println("T3"));
executor.shutdown();
流程图:
flowchart LR
Executor[单线程池] --> T1 --> T2 --> T3
方法 3:wait()/notifyAll() 机制
通过锁和条件控制线程顺序。
private static final Object lock = new Object();
private static int flag = 1;
Thread t1 = new Thread(() -> {
synchronized (lock) {
while (flag != 1) lock.wait();
System.out.println("T1");
flag = 2;
lock.notifyAll();
}
});
Thread t2 = new Thread(() -> {
synchronized (lock) {
while (flag != 2) lock.wait();
System.out.println("T2");
flag = 3;
lock.notifyAll();
}
});
Thread t3 = new Thread(() -> {
synchronized (lock) {
while (flag != 3) lock.wait();
System.out.println("T3");
}
});
t1.start();
t2.start();
t3.start();
流程图:
flowchart LR
T1 -->|notifyAll| T2 -->|notifyAll| T3
方法 4:CompletableFuture 链式调用
利用 CompletableFuture 的任务编排能力。
CompletableFuture.runAsync(() -> System.out.println("T1"))
.thenRun(() -> System.out.println("T2"))
.thenRun(() -> System.out.println("T3"))
.join(); // 等待所有任务完成
流程图:
flowchart LR
T1 -->|thenRun| T2 -->|thenRun| T3
总结
| 方法 | 核心机制 | 适用场景 |
|---|---|---|
join() | 线程阻塞等待 | 简单顺序控制 |
| 单线程池 | 任务队列 FIFO | 异步任务顺序提交 |
wait()/notify() | 锁与条件变量 | 复杂条件依赖 |
CompletableFuture | 异步任务编排 | 现代链式编程(推荐) |
选择方法时,优先考虑 CompletableFuture 或单线程池,它们更简洁且避免手动同步的复杂性。