Differences and connections between wait, sleep, and yield with Java Multithreading

Source: Internet
Author: User

These three methods are commonly used in Java multi-threaded programming and are used to give the execution right of the current thread. Their differences are as follows:


1. Wait is the method of the object, and sleep and yield are the methods of the thread object.


2. Wait releases the lock occupied by the current thread and must be called in the synchronization block. The other two methods do not release the lock and do not need to be called in the synchronization block.


3. Wait allows the current thread to wait for a period of time before re-execution, or wait until other threads call y/yyall to wake up the current thread and then execute.


4. Sleep "sleep" the current thread for a period of time, so that other threads can obtain execution opportunities, including threads with lower priority.


5. Wait and sleep all block the current thread, but yield does not. yield only gives the CPU ownership, however, the current thread is still executable and yield then, the system checks whether there are executable States with the same priority. If yes, it gives the CPU execution permission to this thread; otherwise, it continues to run the current thread, that is, yield is only an opportunity for threads with the same priority to execute, after yield is called, the current thread may not be affected to continue running.

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.