/**
* 线程A 线程B
* A打印a B打印b
* AB交替打印各50次
*/
public class Test {
static final Object room = new Object();
static boolean hasCigarette = true;
public static void main(String[] args) throws InterruptedException {
new Thread(() -> {
synchronized (room) {
int index = 0;
while (index <= 49) {
if (!hasCigarette) {
try {
room.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("b-" + index);
hasCigarette = false;
index++;
room.notify();
}
}
}, "B").start();
new Thread(() -> {
synchronized (room) {
int index = 0;
while (index <= 49) {
if (hasCigarette) {
try {
room.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("a-" + index);
hasCigarette = true;
index++;
room.notify();
}
}
}, "A").start();
}
}
多线程交替打印50次
于 2023-07-02 15:01:31 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)