我有一个类,在我的主方法中,我创建了一个同一个类的实例,并在该实例上调用wait方法,在这种情况下会发生什么?
答案 0 :(得分:2)
它将永远等待:http://ideone.com/bjUe6Y
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
System.setErr(System.out);
System.out.println("Start");
Ideone i = new Ideone();
synchronized (i)
{
i.wait();
}
System.out.println("Done");
}
public Ideone() throws Exception
{
System.out.println("Instanciated");
}
}
但是,如果您不在对象上进行同步,则会抛出IllegalMontiorStateException
Exception in thread "main" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:503)
at Ideone.<init>(Main.java:20)
at Ideone.main(Main.java:14)
http://ideone.com/ceZYTQ(在构造函数内等待)