Java线程:等待不按预期工作

Pet*_* Xu 2 java multithreading wait

当我学习如何使用wait和notify时,我得到一个奇怪的东西,下面两部分代码是相似的,但是它们的结果是如此不同,为什么呢?

class ThreadT implements Runnable{



public void run()
  {
    synchronized (this) {

        System.out.println("thead:"+Thread.currentThread().getName()+" is over!");

    }

   }
}

public class TestWait1 {


public static void main(String[] args) {

    Thread A = new Thread(new ThreadT(),"A");
     A.start();
    synchronized (A) {

        try {
            A.wait();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    System.out.println(Thread.currentThread().getName()+" is over");

}

}
Run Code Online (Sandbox Code Playgroud)

结果:
thead:A结束了!
主要结束了

class ThreadD implements Runnable{

Object o  ;

public ThreadD(Object o)
{
    this.o = o;
}

public void run()
{
    synchronized (o) {

        System.out.println("thead:"+Thread.currentThread().getName()+" is over!");

    }


}
}

public class TestWait2 {


public static void main(String[] args) {

        Object o = new Object();

    Thread A = new Thread(new ThreadD(o),"A");

     A.start();

    synchronized (o) {

        try {
            o.wait();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    System.out.println(Thread.currentThread().getName()+" is over");

}

}
Run Code Online (Sandbox Code Playgroud)

结果:
thead:A结束了!

为什么主函数可以在第一个样本中完成,但第二个样本主函数不能.它们有什么不同?

yol*_*ole 7

如果你在一个Object上调用wait(),它会等待,直到调用notify()为止.在你的第二个例子中,没有人调用notify(),所以等待会永远持续下去.在第一个例子中,线程的终止在其上调用notifyAll(),这导致wait()完成.