Thread.Sleep () vs Thread.yield ()

Source: Internet
Author: User


Thread.Sleep ()
    1. The current thread changes state from Running to waiting/blocked as shown in the diagram below.
    2. Any and thread with reference to the thread currently sleeping (say T) can interrupt it callingt.interrupt()
      • The call to sleep have to is encapsulated to catch the checked exception ofInterruptedException
    3. After the time period for which the thread is set to sleep it goes to the Runnable state andmight not run immediately ! It has a to-wait for the Thread Scheduler to schedule it time slice.
Thread.yield ()
    1. Calling it may cause the thread Scheduler to move the current Thread from Running toRunnable St Ate and execute another same priority thread which is in Runnable state. This transition of the state takes place only if there are some other thread of the same priority in Runnable state. Hence the no guarantee that the thread would stop execution as the criteria of another same priority thread might Not being met.
    2. .yield()is much based on the Thread priorities concept. (All thread was assigned priorities and when a thread of higher priority was in the Runnable state it ususally preempts/stops Execution of lower priority threads depending on implementation of ThreadScheduler.)

Note:

    • Both and is Thread.sleep() Thread.yield() static functions and affect the current thread executing it.
    • Both the functions won't let go to the synchronized locks they hold.

Thread.Sleep () vs Thread.yield ()

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.