Multithreading priority:
The priority of multithreading is 1-10. The larger the number is, the higher the priority is.
If a thread does not set priority, the default priority is 5;
/** * The minimum priority that a thread can have. */ public final static int MIN_PRIORITY = 1; /** * The default priority that is assigned to a thread. */ public final static int NORM_PRIORITY = 5; /** * The maximum priority that a thread can have. */ public final static int MAX_PRIORITY = 10;
These are the three priority constants provided by the Thread class.
The priority setting method is to call the setPriority() method on the Thread object or the object inheriting the Thread class.
Example:
package com.xm.thread.t_19_01_26; import java.util.concurrent.TimeUnit; public class PriorityThread { public static void main(String[] args) throws InterruptedException { HightPriorityThread hightPriorityThread = new HightPriorityThread(); LowPriorityThread lowPriorityThread = new LowPriorityThread(); hightPriorityThread.setPriority(Thread.MAX_PRIORITY); lowPriorityThread.setPriority(Thread.MIN_PRIORITY); lowPriorityThread.start(); hightPriorityThread.start(); TimeUnit.SECONDS.sleep(1); System.out.println("Default priority!"); } } class HightPriorityThread extends Thread{ @Override public void run() { try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("High priority!"); } } class LowPriorityThread extends Thread{ @Override public void run() { try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Low priority!"); } }
Operation result:
Results of the first operation:
High priority!
Default priority!
Low priority!
Results of the second operation:
Default priority!
High priority!
Low priority!
Results analysis:
Although the priority can be set, we can see from the above running results that it does not really control the scheduling order of threads on the CPU.