目录
- 方法一:使用synchronized和wait/notify
- 方法二:使用`CompletableFuture`实现
方法一:使用synchronized和wait/notify
package com.demo;
import java.util.concurrent.CompletableFuture;
public class PrintABC {
// 当前状态
private static String state = "A";
// 共享锁对象
private static final Object lock = new Object();
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
synchronized (lock){
System.out.println("current: A; state: " + state);
// 等待
while (!"A".equals(state)){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("A: " + Thread.currentThread());
// 修改B状态
state = "B";
// 唤醒下一个
lock.notifyAll();
}
});
Thread t2 = new Thread(() -> {
synchronized (lock){
System.out.println("current: B; state: " + state);
// 等待
while (!"B".equals(state)){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("B: " + Thread.currentThread());
// 修改B状态
state = "C";
// 唤醒下一个
lock.notifyAll();
}
});
Thread t3 = new Thread(() -> {
synchronized (lock){
System.out.println("current: C; state: " + state);
// 等待
while (!"C".equals(state)){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("C: " + Thread.currentThread());
// 修改B状态
state = "";
// 唤醒下一个
lock.notifyAll();
}
});
t1.start();
t2.start();
t3.start();
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.
- 65.
- 66.
- 67.
- 68.
- 69.
- 70.
- 71.
- 72.
- 73.
- 74.
- 75.
- 76.
- 77.
- 78.
- 79.
- 80.
- 81.
- 82.
- 83.
- 84.
- 85.
- 86.
输出
方法二:使用CompletableFuture
实现
package com.demo;
import java.util.concurrent.CompletableFuture;
public class PrintABC {
public static void main(String[] args) {
CompletableFuture<Void> t1 = CompletableFuture.runAsync(() -> {
System.out.println("A: " + Thread.currentThread());
});
CompletableFuture<Void> t2 = t1.thenRunAsync(() -> {
System.out.println("B: " + Thread.currentThread());
});
t2.thenRunAsync(()->{
System.out.println("C: " + Thread.currentThread());
});
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
输出
参考
华为OD面试:三个线程交替打印ABC如何实现? 面试题:三个线程如何交替打印ABC100次