【发布时间】:2017-12-27 06:43:42
【问题描述】:
我正在尝试学习多线程的基本概念。
为什么我的乒乓程序只打印 Ping0 和 Pong0,为什么 notify() 没有启动处于等待状态的 Ping 线程?
public class PingPong 实现 Runnable { 串词;
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() 并且它正在打印 ping pong 直到循环结束。但这能保证它会按顺序打印吗?
为什么wait()后跟notify()不要求ping1线程开始执行?
【问题讨论】:
标签: multithreading