<分区>
即使在通知当前线程(使用 this)后,下面的代码也不会执行。
public synchronized void test() {
String str = new String();
try {
System.out.println("Test1");
this.wait();
this.notifyAll();
System.out.println("Test2");
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Inside exception");
e.printStackTrace();
}
}
我在控制台上只得到 Test1
作为输出。
在第二种情况下,如果我在字符串对象上调用 wait 方法,我会得到异常。原因是因为字符串类对象 str
没有锁定当前对象。但我想知道 str.wait()
到底是什么意思?
public synchronized void test() {
String str = "ABC";
try {
System.out.println("Test1");
str.wait();
str.notifyAll();
System.out.println("Test2");
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Ins");
e.printStackTrace();
}
}
控制台输出:
> Test1
java.lang.IllegalMonitorStateException