IllegalMonitorStateException on notify() when synchronized on an Integer

冷暖自知 提交于 2019-11-28 02:17:32

This

private static Integer state = 0;

is equivalent to

private static Integer state = Integer.valueOf(0);

The invocation of valueOf(0) returns a reference to an Integer object, call it A.

You then do

synchronized(state) {

your thread acquires the lock on the object referenced by state, currently that is A.

You then do

state = 1;

which is equivalent to

state = Integer.valueOf(1);

which gives you a different reference to an Integer object, call it B, and assigns it to state. When you then call

state.notify();

you're invoking notify() on an object, B, for which your thread doesn't own the monitor. You can't call notify or wait on objects for which your thread doesn't own the monitor.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!