Sleep and yield

Source: Internet
Author: User
Tags time in milliseconds
Yield
public static void Yield ()
Pauses the currently executing thread object and executes another thread.

Sleep

public static void sleep (long Millis)
                  throws Interruptedexception
Lets the currently executing thread hibernate (suspend execution) within the specified number of milliseconds, which is affected by the system timer and scheduler precision and accuracy. The thread does not lose ownership of any monitor.

Parameters:

Millis-The sleep time in milliseconds.


Package com.icss.biz.ppt;


/**
* Yield: Pauses the currently executing thread object and executes other threads
* @author XIAOHP
*
*/
public class Yieldthread implements runnable{
Private Integer x=0;

@SuppressWarnings ("Static-access")
public void Run () {
for (int i=0;i<50;i++) {
Thread.CurrentThread (). yield (); Note this sentence, other threads may not be able to grab, if the comment out may be
SYSTEM.OUT.PRINTLN (thread ID + thread.currentthread (). GetId () + ": x=" +x);
x + +;
}

}

public static void Main (string[] args) {
Yieldthread YT = new Yieldthread ();
New Thread (YT). Start ();
New Thread (YT). Start ();
}

}

Thread.CurrentThread (). yield (); Note this sentence, other threads may not be able to grab, if the comment out may be a thread rob the resource has been occupied, but after the annotation is removed 2 threads almost evenly distributed

And sleep is to let a thread wait a while, will not be robbed by other threads resources.

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.