The difference between the Java multithreaded sleep () method and the Wait () method

Source: Internet
Author: User
Tags thread class

The sleep () method suspends the thread for a period of time, and the Wait () method blocks the thread until it is woken up or the wait time times out.

The difference is specific as follows:

1 different principles

The sleep () method is a static method of the thread class that causes the thread to pause for a period of time until the timer ends and the thread automatically "wakes up". The wait () method is a non-static method of the object class that is used for inter-thread communication so that the thread that currently owns the lock waits until another thread calls the Notify () method (or Notifyall () method). You can also automatically wake up the thread by setting the time-out to be timed.

2 different handling mechanisms for locks

The sleep () method does not involve communication between threads and does not release locks. The wait () method causes the thread to release the lock it occupies.

3 different areas of use

The sleep () method can be placed anywhere, and the Wait () method can only be placed in the synchronization block.

4 whether the catch exception is different

The sleep () method must catch exceptions, and wait (), notify (), and Notifyall () methods do not need to catch exceptions. During the thread sleep process, it is possible for other objects to call its interrupt () method, throwing a interruptedexception exception.

In summary, it is recommended to use the wait () method because the sleep () method does not release the lock and is prone to deadlock problems.

Resources

"Java Programmer interview written book" P149-150

The difference between the Java multithreaded sleep () method and the Wait () method

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.