1. 题目
通过锁或其他方式实现三个线程顺序执行
2. 思路
2.1. 思路一,join()
使用Thread的join()方法,join()方法可以实现等待某个线程执行完毕后,再执行后续代码。三个线程A、B、C,A执行的时候不等待,B执行的时候等待A,C执行的时候等待B。即可实现A、B、C三个线程顺序执行。
2.2. 思路二,CompletableFuture
使用CompletableFuture实现线程任务的编排。
3. 代码实现
使用 join() 实现三个线程顺序执行
public class rt01 {
public static void main(String[] args) {
Thread A = new Thread(new Work(null), "A");
Thread B = new Thread(new Work(A), "B");
Thread C = new Thread(new Work(B), "C");
A.start();
B.start();
C.start();
}
static class Work implements Runnable{
private final Thread beforeThread;
public Work(Thread beforeThread) {
this.beforeThread = beforeThread;
}
@Override
public void run() {
if(beforeThread != null){
try {
beforeThread.join(); // join() 等待beforeThread线程执行完毕,再继续执行
System.out.println(Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
System.out.println(Thread.currentThread().getName());
}
}
}
}
使用CompletableFuture实现三个线程顺序执行
public class rt02 {
public static void main(String[] args) {
Thread A = new Thread(new Work(), "A");
Thread B = new Thread(new Work(), "B");
Thread C = new Thread(new Work(), "C");
CompletableFuture.runAsync(A::start)
.thenRun(B::start)
.thenRun(C::start);
}
static class Work implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
}