3.線程優先級
阿新 • • 發佈:2019-01-26
多線程 ktr except ren maximum 實例 assign class err
多線程優先級:
多線程優先級為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上的調度順序。
3.線程優先級