3.執行緒優先順序
多執行緒優先順序:
多執行緒優先順序為1~10,數字越大,優先順序越高。
一個執行緒不設定優先順序的話,預設優先順序為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;
以上,是Thread類提供的三個優先順序常量。
設定優先順序的方法為,Thread物件或繼承了Thread類的物件,呼叫setPriority( )方法。
例項:
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("預設優先級別!"); } } class HightPriorityThread extends Thread{ @Override public void run() { try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("優先級別高!"); } } class LowPriorityThread extends Thread{ @Override public void run() { try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("優先級別低!"); } }
執行結果:
第1次執行結果:
優先級別高!
預設優先級別!
優先級別低!
第2次執行結果:
預設優先級別!
優先級別高!
優先級別低!
結果分析:
雖然優先級別可以設定,但通過以上執行結果我們可以看出,它並不能真正控制執行緒在CPU上的排程順序。