[code="java"]
class ThreadB extends Thread{
int total = 0;
public void run(){
synchronized(this){
System.out.println("ThreadB is running...");
for(int i=0;i<100;i++){
total += i;
}
System.out.println("total is "+total);
//notify();
}
}
}
public class ThreadA{
public static void main(String args[]){
ThreadB b = new ThreadB();
b.start();
synchronized(b){
System.out.println("Waiting for b to complete...");
try{
Thread.sleep(3000);
b.wait();
}catch(InterruptedException e){}
System.out.println("Completed.Now back to main thread");
}
System.out.println("....Total is:"+b.total);
}
}
/*主线程先得到b的锁,执行到b.wait();的时候,主线程阻塞,释放对象锁,线程b变为运行状态,把notify()注释掉,
没有唤醒主线程,主线程为什么还能继续进行?*/
[/code]
不能解释具体原因,只能猜测 用线程对象wait()的时候,线程对象运行完成后(run()完成退出),所以利用这个线程对象的wait()都退出等待。
写了一个例子:
[code="java"]public class ThreadAa {
public static void main(String args[]){
ThreadB1 t1 = new ThreadB1();
ThreadB2 t2 = new ThreadB2();
ThreadB3 t3 = new ThreadB3();
t2.oo = t1;
t3.oo = t1;
t1.start();
t2.start();
t3.start();
}
}
class ThreadB1 extends Thread {
public Object oo ;
public void run() {
try{Thread.sleep(1000);}catch(Exception e) {};
// while(true) {
// try{Thread.sleep(10);}catch(Exception e) {};
// }
}
}
class ThreadB2 extends Thread {
public Object oo ;
public void run() {
synchronized(oo) {
System.out.println("wait2");
try{oo.wait();} catch(Exception e) {
System.out.println("interrupt2");
}
}
System.out.println("end2");
}
}
class ThreadB3 extends Thread {
public Object oo ;
public void run() {
synchronized(oo) {
System.out.println("wait3");
try{oo.wait();} catch(Exception e) {
System.out.println("interrupt3");
}
}
System.out.println("end3");
}
} [/code]
如果要等待b结束,用b.join()。
你的两个synchronized段没有意义,也不能保证先后顺序。