The difference between wait () and sleep () in Java

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.