关于在Java中为块同步对象的混淆

关于在Java中为块同步对象的混淆,java,object,locking,wait,synchronized,Java,Object,Locking,Wait,Synchronized,输出 public class ThreadConfusion { public static void main(String[] args) { System.out.print("1 "); synchronized (args) { System.out.println(" 2"); try { args.wait()

输出

public class ThreadConfusion
{
    public static void main(String[] args) 
    {
        System.out.print("1 ");
        synchronized (args) 
        {
            System.out.println(" 2");
            try
            {
                args.wait();
            }
            catch (InterruptedException e)
            {
                System.out.println("exception");
            }
        }
        System.out.println("3 ");
    } //end of the main method
} // end of the class

为什么输出是1 2而不是1 2 3。那边到底发生了什么?

因为没有人调用
notify()
。主线程将无限期地等待

wait()
的javadoc中:

使当前线程等待,直到另一个线程调用 此对象的notify()方法或notifyAll()方法

如果要等待,请调用
Thread.sleep()

使当前线程等待,直到另一个线程为此对象调用notify()方法或notifyAll()方法

您正在告诉
等待
(锁定对象)线程(
main

给予

并查看等待在5秒后结束并打印
3


或者调用
notify()

为什么调用wait()?更重要的是,它在等待您调用notify():您希望调用谁
args.notify()
?这里没有其他线程。。。
1  2
args.wait();
  try{args.wait(5000);}