private void testWait(){
Thread thread = new Thread(() -> {
synchronized (Log.class) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
}
當我們執行上面一段代碼的時候會出現IllegalMonitorStateException 咋一看沒問題啊 wait是在同步方法裏啊 咋還報着異常了 但是當仔細看時發現鎖對象和調用wait方法的對象不是同一對象 當出現這一情況時就會拋該異常 可以做以下更改
private void testWait(){
Thread thread = new Thread(() -> {
synchronized (Log.class) {
try {
Log.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
}