ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

使用三个线程按顺序打印ABC,循环打印10次

使用三个线程按顺序打印ABC,循环打印10次

记录一道常用的线程调度算法题

实现如下:

public class PrintABC {
private static final int MAX_PRINT_COUNT = 10; // 循环打印次数
private static int state = 0; // 线程状态,0表示打印A,1表示打印B,2表示打印C

public static void main(String[] args) {
Object lock = new Object();

Thread threadA = new Thread(() -> {
for (int i = 0; i < MAX_PRINT_COUNT; i++) {
synchronized (lock) {
while (state % 3 != 0) { // 轮到A打印
try {
lock.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.print("A");
state++;
lock.notifyAll();
}
}
});

Thread threadB = new Thread(() -> {
for (int i = 0; i < MAX_PRINT_COUNT; i++) {
synchronized (lock) {
while (state % 3 != 1) { // 轮到B打印
try {
lock.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.print("B");
state++;
lock.notifyAll();
}
}
});

Thread threadC = new Thread(() -> {
for (int i = 0; i < MAX_PRINT_COUNT; i++) {
synchronized (lock) {
while (state % 3 != 2) { // 轮到C打印
try {
lock.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.print("C");
state++;
lock.notifyAll();
}
}
});

// 启动三个线程
threadA.start();
threadB.start();
threadC.start();
}
}

返回列表