Confusion between sleep() and wait()

This question already has an answer here:

  • Difference between wait() and sleep() 33 answers

  • Difference between wait and sleep in Java :

  • wait release lock on object while waiting while sleep doesn't release lock while waiting.
  • wait is normally done on condition, Thread wait until a condition is true while sleep is just to put your thread on sleep.
  • wait is called from synchronized context only while sleep can be called without synchronized block. see Why wait and notify needs to call from synchronized method for more detail.
  • wait is called on Object while sleep is called on Thread. see Why wait and notify are defined in object class instead of Thread.
  • waiting thread can be awake by calling notify and notifyAll while sleeping thread can not be awaken by calling notify method.

  • 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.

  • 链接地址: http://www.djcxy.com/p/92138.html

    上一篇: 用java获取正在运行的bash脚本的输出

    下一篇: 睡眠()和等待()之间的混淆