For wait and sleep it would seem to block threads, but they are really a big difference, so here's a little bit of discussion:
- Difference one, Sleep () is the method inside the thread, and wait () is the method of the object class.
This is relatively simple, directly read the code will know:
- The difference between the sleep () method does not need to be awakened by the Notify, while wait () requires "Of course wait (10) except in such cases".
This is easier to understand, not much to explain.
- Sleep () use is not required to use syncronized plus a sync lock, but wait () is required.
This is an experiment to understand:
Well, you don't need to add a sync block when you call sleep (), and then look at Wait ():
OK, then fix this exception:
- Sleep () does not release the sync lock, but wait () is released.
This is not very good understanding, the following experiments to verify:
And when the thread is finished with a sleep (), the line Cheng to the lock.
OK, then change to wait () and look at the result:
See the wood, equal to two threads executed simultaneously, that is, during the thread a wait (), its lock is released can be obtained by other threads.
Java Thread Foundation Consolidation---What is the essential difference between wait and sleep, in-depth analysis (interview FAQs)