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.