The point here is to be clear, no matter how programmers write scheduling, can only maximize the impact of thread execution order, but not accurate control.
The purpose of thread hibernation is one of the easiest ways for a thread to give up the CPU, when the thread sleeps, it gives the CPU resources to other threads so that it can rotate, and when it sleeps for a certain time, the line Cheng wakes up and waits for execution.
The method of thread hibernation is thread.sleep (long Millis) and Thread.Sleep (long millis, int nanos), all static methods, which thread that calls sleep hibernation? Simply put, which thread calls sleep, sleeps which thread.
/**
* java thread: Thread scheduling-Hibernate
*
* @author leizhimin
*/
public class Test {
public static void Main (string[] args) {
Thread t1 = new MyThread1 ();
Thread t2 = new Thread (new myrunnable ());
T1.start ();
T2.start ();
}
}
Class MyThread1 extends Thread {
public void run () {
for int i = 0; I < 3; i++) {
System.out.println ("Thread 1" + i + "secondary execution!") ");
try {
Thread.Sleep;
catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
Class Myrunnable implements Runnable {
public void run () {
for (int i = 0; i < 3; i++) {
System.out. println ("Thread 2" + i + "secondary execution!") ");
try {
Thread.Sleep;
catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
线程2第0次执行!
线程1第0次执行!
线程1第1次执行!
线程2第1次执行!
线程1第2次执行!
线程2第2次执行!
Process finished with exit code 0
From the results above, it can be seen that the thread execution order cannot be guaranteed accurately.
Source: http://lavasoft.blog.51cto.com/62575/221790