繁体   English   中英

如何在Java中从用户线程通知正在等待的主线程?

[英]how to notify waiting main thread from user thread in java?

class A implements Runnable
{
  public void run()
  {
    try
    {
      Thread.sleep(1000);
    }
    catch(Exception e){};
    notify();//This has to wake up the sleeping main thread.
  }
  public static void main(String args[])
  {
    A a=new A();
    Thread t=new Thread(a);
    t.start();
    try
    {
      Thread.wait(5000);
    }
    catch(Exception e){};
    System.out.println("Rest of the code");
  }
}

当我编译此代码时,JVM表示无法从静态主方法中引用非静态方法等待。

当我将其放在其他方法中时,它将显示非法的监视器异常。

请为我提出解决此问题的方法。 不要建议加入。 因为我必须等待并且单独通知。

几件事情:

  • wait方法属于Object而不是线程。
  • wait方法不是静态方法,因此您不能使用ClassName.wait
  • 为了等待工作,您需要在获取对象的监视器之前,否则获取IllegalMonitorException。

请参阅以获取有关wait api的详细信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM