简体   繁体   English

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

[英]Java Threads: Wait don't work as expected

I get a strange thing when I learn how to using wait and notify, the below two parts code are similar, but their result are so different, why? 当我学习如何使用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");

}

}

Result: 结果:
thead:A is over! thead:A结束了!
main is over 主要结束了

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");

}

}

Result: 结果:
thead:A is over! thead:一个结束了!

why the main function can finish in the first sample, but the second sample main function can't. 为什么主函数可以在第一个样本中完成,但第二个样本主函数不能。 what are they different? 它们有什么不同?

If you're calling wait() on an Object, this waits until something calls notify() on it. 如果你在一个Object上调用wait(),它会等待,直到调用notify()为止。 In your second example, there is no one calling notify(), so the wait goes on forever. 在你的第二个例子中,没有人调用notify(),所以等待会永远持续下去。 In the first example, the termination of the thread calls notifyAll() on it , which causes the wait() to complete. 在第一个例子中,线程的终止在其上调用notifyAll() ,这导致wait()完成。

@yole is right. @yole是对的。 On "Object o" no body calls notify but in first case in which you are waiting on Thread instance notifyall is called by Thread instance when it exits. 在“对象o”上没有主体调用通知,但在第一种情况下,您正在等待线程实例notifyall在退出时由Thread实例调用。

Here is another web link which refers to same question you have asked. 这是另一个Web链接 ,指向您提出的相同问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM