即使在通知当前线程之后,下面的代码也不会执行(使用此).
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();
}
}
Run Code Online (Sandbox Code Playgroud)
我只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();
}
}
Run Code Online (Sandbox Code Playgroud)
控制台输出:
> Test1
java.lang.IllegalMonitorStateException
Run Code Online (Sandbox Code Playgroud)