The difference between sleep and wait in Java

Source: Internet
Author: User

This question is essentially a must-ask question when interviewing for thread-related knowledge. Therefore, it is necessary to make a more detailed summary.

Distinguish one

The first thing to understand is that these two methods come from different classes at all, and sleep comes fromthread,wait from the object class .

Sleep is a static method provided by thread that appears in that thread, and that thread "sleeps", not

Call the method of the thread to sleep, for example a thread in the call Thread B.sleep (), a thread to sleep.

Difference Two

The main difference is that the sleep method does not release the "lock", and the Wait method releases the "lock" otherwise it will form a deadlock.

Sleep does not yield system resources; When wait is a thread interaction, if thread A sends a wait to a synchronization object X

Calling the thread will enter the thread waiting for the pool to wait, wait for other threads to call Notify/notifyall wake, or after the specified time

Automatic wake-up.

It is also important to understand that either the time of the sleep setting or the wait is awakened, and the thread

Does not necessarily resume immediately, but instead triggers the "operating system to re-compete with the CPU."

Difference Three

Use a different range (this is slightly farfetched as the difference)

Wait, Notify/notifyall must be used in the synchronization control block, synchronous method. And sleep is used in any place.

Synchronized (x) {
X.notify ()
or wait ()
}

Difference Four

the code behaves that sleep must catch an exception, and wait does not need to catch the exception.

The difference between sleep and wait in Java

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.