如何从java中的用户线程通知等待主线程?

时间:2015-01-24 16:46:46

标签: java multithreading synchronization wait

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说非静态方法等待不能从静态main方法引用。

当我把它放在另一种方法中时,它会显示非法的监视器异常。

请建议我解决这个问题的方法。不要建议像加入这样的东西。因为我必须等待并单独通知。

1 个答案:

答案 0 :(得分:2)

一些事情:

  • wait方法属于Object而不是thread。
  • wait方法不是静态方法,因此您无法使用ClassName.wait
  • 等待工作,你需要先获取对象的监视器,否则你会得到IllegalMonitorException。

有关wait api的详细信息,请参阅this