两个线程交替打印(wait/notify)
public class Alternately {
private volatile Boolean preIsA = false;
synchronized void backA() {
try {
while (preIsA == true) {
wait();
}
for (int i = 0; i < 5; i++) {
System.out.println("💗💗💗💗💗");
}
preIsA = true;
notifyAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized void backB() {
try {
while (preIsA == false) {
wait();
}
for (int i = 0; i < 5; i++) {
System.out.println("🌙🌙🌙🌙🌙");
}
preIsA = false;
notifyAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//Thread A = new Thread(()-> backA());
}
@Test
public void testMethod() {
for (int i = 0; i < 5; i++) {
Thread A = new Thread(() -> backA());
Thread B = new Thread(() -> backB());
A.start();
B.start();
}
}
}