java怎么使用wait(), notify(), notifyAll()来实现三个线程轮流执行的效果
时间: 2023-11-13 13:04:47 浏览: 28
可以通过以下代码实现三个线程轮流执行的效果:
```java
public class ThreeThread {
private int count = 0;
private final Object lock = new Object();
public static void main(String[] args) {
ThreeThread threeThread = new ThreeThread();
Thread threadA = new Thread(() -> threeThread.print("A", 0));
Thread threadB = new Thread(() -> threeThread.print("B", 1));
Thread threadC = new Thread(() -> threeThread.print("C", 2));
threadA.start();
threadB.start();
threadC.start();
}
private void print(String name, int flag) {
synchronized (lock) {
while (count % 3 != flag) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(name);
count++;
lock.notifyAll();
}
}
}
```
其中,count 用于记录当前轮到哪个线程执行,lock 是用来实现多线程同步的对象。在每个线程的执行体中,使用 synchronized (lock) 来加锁保证线程间的互斥。在 while 循环中判断当前轮到哪个线程执行,如果不是当前线程轮到,则使用 lock.wait() 阻塞当前线程。在轮到当前线程执行后,执行相应的操作(例如输出线程名),然后将 count 加一,再使用 lock.notifyAll() 通知所有在等待的线程重新进行判断。这样就可以循环执行三个线程。