This article illustrates the thread hibernation usage of Java thread scheduling. Share to everyone for your reference. The specific analysis is as follows:
Java thread scheduling is the core of Java multithreading, only good scheduling, can give full play to the performance of the system, improve the execution efficiency of the program.
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 Dispatch-Hibernate
*
* @author leizhimin 2009-11-4 9:02:40/
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 () {to
(int i = 0; i < 3; i++) {
System.out.println ("line Process 1 "+ i +" secondary execution! ");
try {
thread.sleep (m);
} catch (Interruptedexception e) {
e.printstacktrace ()
}}}
class Myrunnable implements Runnable {public
void run () {for
(int i = 0; i < 3; i++) {
SYSTEM.O UT.PRINTLN ("Thread 2" + i + "secondary execution!") ");
try {
thread.sleep (m);
} catch (Interruptedexception e) {
e.printstacktrace ()
}}}}
The results of the operation are as follows:
Thread 2 executes for the NO. 0 time!
Thread 1 executes for the NO. 0 time!
Thread 1 executes for the 1th time!
Thread 2 executes for the 1th time!
Thread 1 executes for the 2nd time!
Thread 2 executes for the 2nd time!
Process finished with exit code 0
The
Output from the results above shows that the thread execution order cannot be accurately guaranteed.