This article analyzes the dormant usage of threads scheduled by the Java thread. Share it for everyone for your reference. The specific analysis is as follows:
The Java thread scheduling is the core of Java multi -threaded. Only good scheduling can give full play to the performance of the system and improve the implementation efficiency of the program.
It is clear that no matter how the programmer writes the scheduling, it can only affect the order of thread execution to the greatest extent, and cannot be accurately controlled.
The purpose of thread dormancy is to make the thread make the simplest approach of the CPU. When the thread is dormant, the CPU resources will be handed over to other threads to rotate. implement.
The method of thread dormancy is Thread.sleep (Long Millis) and Thread.sleep (Long Millis, Int Nanos), both of which are static methods. Which thread to call Sleep's dormant? To put it simply, which thread is called for Sleep, you can sleep.
/ ** * Java thread: thread scheduling-dormant * @Author leizhimin 2009-11-4 9:02:40 */ Public Class test {Public Static void Main (String [] ARGS) {thread T1 = New Rea D1 (D1 ( ); 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 + "is executed!"); Try {thread.sleep (50);} Catch (interruptedException E) {e.printstacktrace ();}}}}}}}}}}}}} class myrunnable images runnable {public void run () {for (int i = 0; i <3; i ++) {system.out.println ("thread 2" + i + "secondary execution!"); Try {Thread. SLEEP (50);} Catch (InterruptedException E) {e.printstacktrace ();}}}}The results are as follows:
Performance of thread 2! Period of thread 1! Performance of thread 1 for the first time! The first execution of thread 2! Performance of thread 1 for the second time! Period of thread 2! Process Finished with EXIT CODE 0
From the above results output, it can be seen that the order of thread execution cannot be accurately guaranteed.