为什么在线程完成时在线程对象上调用`wait`会解除阻塞?

时间:2019-01-30 04:21:45

标签: java multithreading

代码是

    private static final MyThread myThread = new MyThread();

    public static void main(String[] args) {
        synchronized (myThread) {
            System.out.println("1");
            myThread.start();
            System.out.println("2");
            try {
                myThread.wait();
                System.out.println("3");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    static class MyThread extends Thread {
        public MyThread() {
            super("thread lock");
        }

        @Override
        public void run() {
            synchronized (myThread) {
                System.out.println("4");
            }

        }

    }

代码打印为:
1个
2
4
3

通过调试,我发现在thread lock的运行方法之后 thread main的等待状态已中断。

public static void main(String[] args) {
        myThread.start();
        synchronized (myThread) {
            System.out.println("1");
//            myThread.start();
            System.out.println("2");
 .....
 .....

如果线程在myThread.start()之前开始synchronized,并且thread lock以断点结束, myThread.wait()将永远等待, 我怀疑在run()的结尾处,对`notifyAll()的调用是隐藏的。

0 个答案:

没有答案