In the operating system, threads can prioritize, and higher-priority threads get more CPU resources-that is, the CPU prioritizes tasks in higher-priority thread objects (not really).
In Java, threads are prioritized with the setpriority () method, the priority of the thread is divided into 1-10 of the 10 levels, and if less than 1 or greater than 10 throws an exception throw new IllegalArgumentException (), default is 5.
public class MyThread1 extends Thread {@Overridepublic void run () {long starttime=system.currenttimemillis (); long addresult=0;for (int i = 0; i < 1000000; i++) {new Random (). Nextint (); addresult+=i;} Long Endtime=system.currenttimemillis (); SYSTEM.OUT.PRINTLN ("Thread1 Use time--->" + (Endtime-starttime));}}
public class MyThread2 extends Thread {@Overridepublic void run () {long starttime=system.currenttimemillis (); long addresult=0;for (int i = 0; i < 1000000; i++) {new Random (). Nextint (); addresult+=i;} Long Endtime=system.currenttimemillis (); SYSTEM.OUT.PRINTLN ("Thread2 Use time--->" + (Endtime-starttime));}}
public class Mythread{public static void Main (string[] args) {for (int i = 0; i < 5; i++) {MyThread1 t1=new MyThread1 (); T1.setpriority (+); T1.start (); MyThread2 t2=new MyThread2 (); t2.setpriority (1); T2.start ();}}
As you can see from the results, there are also thread2 than Thread1, which verifies that the thread's priority is independent of the Code execution order.
public class Mythread{public static void Main (string[] args) {for (int i = 0; i < 5; i++) {MyThread1 t1=new MyThread1 (); T1.setpriority (6); T1.start (); MyThread2 t2=new MyThread2 (); t2.setpriority (5); T2.start ();}}
if we set the priority level closer, we find that the higher priority threads do not have to be executed all at once, and that the priority of the threads is independent of the order of printing, and do not associate the two-point relationship . Their relationship is uncertainty and randomness.
The thread's priority still does not guarantee the thread's execution order. However, high-priority threads have a higher probability of getting CPU resources, and the lower priority is not a chance to execute.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Priority for Java multi-thread threads