问题: 我有两个线程类如下。 我期待我的程序永远不会终止,因为我没有使用wait(long ms)方法。因为我没有调用通知已经获得锁并且处于等待状态的对象应该从未被通知过。
但输出并不符合我的预期。
请帮助我理解这个概念。
我的代码:
ThreadA{
main(String args[]){
ThreadB b = new ThreadB();
b.start();
}
synchronized(b) {
try {
System.out.println("Main thread will start waiting");
b.wait();
System.out.println("Main thread waiting for notification");
System.out.println("wait over!!");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(b.total);
System.out.println("Main thread execution finished!!");
}
}
ThreadB{
int total =0;
public void run() {
synchronized(this) {
for(int i=0;i<=100;i++) {
total=total+i;
}
System.out.println("Child thread should give notification");
//this.notify();
}
System.out.println("Child thread execution finished!!");
}
}
<!--code-->
结果:
Main thread will start waiting
Child thread should give notification
Child thread execution finished!!
Main thread waiting for notification
wait over!!
5050
Main thread execution finished!!