You have noted correctly that notifyAll
must be called from a synchronized block.
However, in your case, because of auto-boxing, the object you synchronized on is not the same instance that you invoked notifyAll
on. In fact, the new, incremented foo
instance is still confined to the stack, and no other threads could possibly be blocked on a wait
call.
You could implement your own, mutable counter on which synchronization is performed. Depending on your application, you might also find that AtomicInteger meets your needs.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…