当我们只使用wait()方法而不是notify()时,程序可以成功终止

时间:2018-04-08 19:18:54

标签: java multithreading

问题:  我有两个线程类如下。  我期待我的程序永远不会终止,因为我没有使用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!!

0 个答案:

没有答案