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();
}