题目:
现有3个线程,线程1无限打印1, 线程2无限打印2,线程3无限打印3,实现3个线程无限循环打印123123...
实现:
使用锁以及线程的等待机制
public class ThreadPrintOrdered {
private static int state = 1;
private static final Object lock = new Object();
// 判断当前状态是否满足, 不满足则当前线程等待
private static void print(int currentState, int nextState) {
while (true) {
synchronized (lock) {
while (state != currentState) {
try {
// 当前线程等待
lock.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.println(currentState);
state = nextState;
// 唤醒所有线程
lock.notifyAll();
}
}
}
public static void main(String[] args) throws Exception{
new Thread(() -> print(1, 2)).start();
new Thread(() -> print(2, 3)).start();
new Thread(() -> print(3, 1)).start();
}
}