Confusion between sleep() and wait()
This question already has an answer here:
Difference between wait and sleep in Java :
Alright I'm going to try to answer this.
If t1
never gets to run again, I'd say the kernel's thread scheduler is broken. I don't know where you got your idea that it would never run again.
If you have two threads making changes to one object, you need to make sure they behave properly. Such as using synchronized
to make sure only one thread manipulates the object at a time. Your example is odd, because you seem to imply that the programmer doesn't decide what happens with the code.
You don't understand wait()
and notify()
. Search for a question about them, there's plenty.
wait()
needs to be in synchronized context to get the object monitor. sleep()
in synchronized context just creates an unnecessary block for other threads wanting to enter.
下一篇: 睡眠()和等待()之间的混淆