我正在尝试创建一个带有两个线程的简单“Ping-Pong”程序(Pong 线程仅在 Ping 线程之后打印他的消息)。
问题是为什么下面的代码一直卡住,但在notifyAll
?
这是我的代码:
public class Main {
private static class Ping extends Thread {
private int rounds;
Ping(int rounds) { this.rounds = rounds; }
@Override
public void run() {
try {
synchronized(this) {
while(rounds > 0) {
System.out.println("Ping");
notify();
wait();
--rounds;
}
notify();
}
System.out.println("Ping done");
} catch(Exception ignored) { ignored.printStackTrace(); }
}
public boolean isDone() { return rounds <= 0; }
}
private static class Pong extends Thread {
private final Ping ping;
Pong(Ping ping) { this.ping = ping; }
@Override
public void run() {
try {
synchronized(ping) {
while(!ping.isDone()) {
System.out.println("Pong");
ping.notify();
ping.wait();
}
}
System.out.println("Pong done");
} catch(Exception ignored) { ignored.printStackTrace(); }
}
}
public static void main(String[] args) throws Exception {
Ping ping = new Ping(15);
Pong pong = new Pong(ping);
ping.start();
pong.start();
ping.join();
pong.join();
}
}