Causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other word's this method behaves exactly as if it simply performs the call wait(0). wait()is not defined in the class Thread ,it is defined in class Objestso there is no diffient between a.wait() and b.wait(),Noted that:
Causes current thread to wait ,you invoke it in ThreadA,so ...
clear to you ?
Causes current thread to wait ,you invoke it in ThreadA,so ...
clear to you ?
2,b.wait()表示放弃所在synchronized{....}语句块对对象b的锁定,此时运行b.run(),直到notify().
3,源代码的写法易引起混淆,事实上,它与一下代码作用一样:
public static void main(String [] args){
ThreadB b = new ThreadB();
b.start();
b.k();
}
}
class ThreadB extends Thread {
...
public run(){...}
public void k(){
synchronized(this){
try {
System.out.println("Waiting for b to complete...");
wait();
System.out.println("waiting");
} catch (InterruptedException e) {}
}
System.out.println("Total is: " + total);
}
..
ThreadB b = new ThreadB();
b.start();
b.k();
}
}
class ThreadB extends Thread {
...
public run(){
synchronized(this){
for(int i=0;i<100;i++) {
total += i;
}
notify();
}
}
public void k(){
synchronized(this){//如果在运行b.start(),则当前块不可进入,直到notify(),对吗?
try {
System.out.println("Waiting for b to complete...");
wait();//b.k()等,b.start()继续进行,对吗?
System.out.println("waiting");
} catch (InterruptedException e) {}
}
System.out.println("Total is: " + total);
}
2,对