0
我想學習多線程的基本概念。PingPong程序Java多線程
爲什麼我的乒乓程序只打印Ping 0 & Pong0,爲什麼notify()不啓動處於等待狀態的Ping線程?
公共類PingPong實現Runnable { String string;
public PingPong(String word) {
this.word = word;
}
public void run() {
synchronized (this) {
for (int i = 0; i < 10; i++) {
System.out.println(word + i);
try {
wait();
notifyAll();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
}
public static void main(String[] args) {
Runnable p1 = new PingPong("ping");
Thread t1 = new Thread(p1);
t1.start();
Runnable p2 = new PingPong("pong");
Thread t2 = new Thread(p2);
t2.start();
}
}
輸出
ping0
pong0
我試圖消除wait()和它的印刷乒乓球,直到循環結束。但是這保證它會按順序打印?
爲什麼wait()跟在notify()不要求ping1線程開始執行?