关于在Java中同步块的对象的困惑

时间:2013-10-10 09:43:18

标签: 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();
            }
            catch (InterruptedException e)
            {
                System.out.println("exception");
            }
        }
        System.out.println("3 ");
    } //end of the main method
} // end of the class

输出

1  2

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

2 个答案:

答案 0 :(得分:0)

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

来自wait()的javadoc:

  

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

如果您想等待电话Thread.sleep();

答案 1 :(得分:0)

args.wait();

wait()

  

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

您要永远告诉wait(锁定对象)threadmain)。

  try{args.wait(5000);}

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

或致电notify()