Thread sleep usage analysis for Java thread scheduling

  • 2020-04-01 03:55:16
  • OfStack

This paper analyzes the usage of thread sleep in Java thread scheduling. Share with you for your reference. Specific analysis is as follows:

Java thread scheduling is the core of Java multithreading, only a good scheduling, can give full play to the performance of the system, improve the execution efficiency of the program.
 
One thing to be clear here is that no matter how the programmer writes the schedule, it can only affect the order of execution of the threads to the greatest extent, and cannot achieve precise control.
 
The purpose of thread hibernation is to make the thread out of the CPU is one of the simplest practices, when the thread hibernation, the CPU resources will be given to other threads, so that the rotation of execution, when the sleep for a certain period of time, the thread will wake up, into a ready state waiting for execution.
 
Thread.sleep(long millis) and thread.sleep (long millis, int nanos) are both static methods. Which Thread is called to sleep? Simply put, the thread that calls sleep will sleep.


 
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 The first " + i + " Perform! "); 
   try { 
    Thread.sleep(50); 
   } catch (InterruptedException e) { 
    e.printStackTrace(); 
   } 
  } 
 } 
} 
class MyRunnable implements Runnable { 
 public void run() { 
  for (int i = 0; i < 3; i++) { 
   System.out.println(" thread 2 The first " + i + " Perform! "); 
   try { 
    Thread.sleep(50); 
   } catch (InterruptedException e) { 
    e.printStackTrace(); 
   } 
  } 
 } 
}

The operation results are as follows:


 thread 2 The first 0 Perform!  
 thread 1 The first 0 Perform!  
 thread 1 The first 1 Perform!  
 thread 2 The first 1 Perform!  
 thread 1 The first 2 Perform!  
 thread 2 The first 2 Perform!  

Process finished with exit code 0

As you can see from the resulting output above, there is no precise guarantee of thread execution order.


Related articles: