The difference between classes
- Wait () comes from
java.lang.Object
, any object has this method
- Sleep () comes from
java.lang.Thread
, the object being called is a thread
The difference in usage
Take a look at the JDK description:
wait()
: Causes the current thread to wait until either another thread invokes the
Java.lang.Object.notify () method or the Java.lang.Object.notifyAll () method for this Object, or a specified amount of time has elapsed.
Suspends the current thread, java.lang.Object.notify()
java.lang.Object.notifyAll()
resumes execution from wait () when the object is called or the time expires
sleep()
: Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, Su Bject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.
Sleeps the currently executing thread for a specified period of time (pauses execution)
Sync is different from lock
The main difference between wait () and sleep () is that synchronization and locking, Wiat () must be placed in the synchronized block, otherwise the program runtime will throw an java.lang.IllegalMonitorStateException
exception.
- Wait () Period object lock is released
When the call to sleep () is not released, the call to yield () also belongs to this situation
synchronized(LOCK) { Thread.sleep(1000); // LOCK is held}synchronized(LOCK) { LOCK.wait(); // LOCK is not held}
In general, wait () is used for communication between threads, and sleep () is used for control of thread state
Resources
Http://stackoverflow.com/questions/1036754/difference-between-wait-and ...
http://howtodoinjava.com/2013/03/08/difference-between-sleep-and-wait/
http://www.qat.com/using-waitnotify-instead-thread-sleep-java/
The difference between wait () and sleep () in Java