【问题标题】:confusion about synchronizing an object for a block in Java关于在 Java 中为块同步对象的困惑
【发布时间】:2013-10-10 09:43:17
【问题描述】:
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。那边到底发生了什么?

【问题讨论】:

  • 你为什么叫 wait() ?它在等你调用 notify()
  • 更重要的是:您希望给谁打电话args.notify()?这里没有其他线程...

标签: java object locking wait synchronized


【解决方案1】:

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

来自wait()的javadoc:

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

如果您想等待,请致电Thread.sleep()

【讨论】:

    【解决方案2】:
    args.wait();
    

    wait()

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

    你说wait(锁定对象)永远是threadmain)。

      try{args.wait(5000);}
    

    并看到等待在 5 秒后完成并打印 3

    或致电notify()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-14
      • 2014-09-03
      • 2020-05-04
      • 2020-09-22
      • 1970-01-01
      • 2012-07-09
      相关资源
      最近更新 更多