问题描述: 确保线程 T2 在 T1 执行完后执行,T3 在 T2 执行完后执行。
解决思路同三个线程交替打印ABC,以下给出其他思路:
方案一:join()
public class ThreadJoinExample {
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
System.out.println("T1 is running");
});
Thread t2 = new Thread(() -> {
try {
t1.join();
System.out.println("T2 is running");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
Thread t3 = new Thread(() -> {
try {
t2.join();
System.out.println("T3 is running");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
t1.start();
t2.start();
t3.start();
}
}
方案二:CountDownLatch
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
public static void main(String[] args) {
CountDownLatch latch1 = new CountDownLatch(1);
CountDownLatch latch2 = new CountDownLatch(1);
Thread t1 = new Thread(() -> {
System.out.println("T1 is running");
latch1.countDown(); // T1完成后,latch1计数器减1
});
Thread t2 = new Thread(() -> {
try {
latch1.await(); // 等待T1完成
System.out.println("T2 is running");
latch2.countDown(); // T2完成后,latch2计数器减1
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
Thread t3 = new Thread(() -> {
try {
latch2.await(); // 等待T2完成
System.out.println("T3 is running");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
t1.start();
t2.start();
t3.start();
}
}
方案三:CompletableFuture
import java.time.LocalDateTime;
import java.util.concurrent.CompletableFuture;
public class CompletableFutureExample {
private static void printWithStamp(String value, long sleepTime) {
try {
System.out.println(LocalDateTime.now() + ": " + value);
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) {
// 创建并启动线程T1
CompletableFuture<Void> t1 = CompletableFuture.runAsync(() ->
printWithStamp("T1 is running", 300));
// 创建并启动线程T2,依赖于线程T1的完成
CompletableFuture<Void> t2 = t1.thenRunAsync(() ->
printWithStamp("T2 is running", 200));
// 创建并启动线程T3,依赖于线程T2的完成
CompletableFuture<Void> t3 = t2.thenRunAsync(() ->
printWithStamp("T3 is running", 100));
// 等待所有线程完成
t3.join();
}
}
1709

被折叠的 条评论
为什么被折叠?



