1. 如何用java解决:启动三个线程,依次打印“A”, “B”, “C” ?
2. 代码:
package com.nami.algorithm.study.thread;
import java.util.concurrent.TimeUnit;
/**
* 描述: 通过wait notifyAll 方法解决依次打印问题。
* 对num求模取余解决哪个线程输出结果
*
* @Author: lbc
* @Date: 2024-02-22 10:59
* @email: 594599620@qq.com
* @Description: keep coding
*/
public class ABCPrintingThreads {
private static final Object lock = new Object();
private static int num = 3;
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
while (true) {
try {
synchronized (lock) {
if (num % 3 == 0) {
// System.out.println("当前线程:" + Thread.currentThread().getName());
System.out.println("A");
num++;
lock.notifyAll();
}
}
} catch (Exception e) {
}
}
}, "t1");
Thread t2 = new Thread(() -> {
while (true) {
try {
synchronized (lock) {
if (num % 3 == 1) {
// System.out.println("当前线程:" + Thread.currentThread().getName());
System.out.println("B");
num++;
lock.notifyAll();
}
}
} catch (Exception e) {
}
}
}, "t2");
Thread t3 = new Thread(() -> {
while (true) {
try {
synchronized (lock) {
if (num % 3 == 2) {
// System.out.println("当前线程:" + Thread.currentThread().getName());
System.out.println("C");
num++;
lock.notifyAll();
}
}
} catch (Exception e) {
}
}
}, "t3");
t1.start();
// Thread.sleep(30);
// 保持顺序启动
TimeUnit.MICROSECONDS.sleep(30);
t2.start();
TimeUnit.MICROSECONDS.sleep(30);
t3.start();
TimeUnit.MICROSECONDS.sleep(30);
}
}
3. 有很多方法都可以解决。如信号量,LockSupport, join等