【多線程】線程優先級 Priority
線程優先級 Priority
-
Java提供一個線程調度器來監控程序中啟動后進入就緒狀態的所有線程,線程調度 器按照優先級決定應該調度哪個線程來執行。
-
線程的優先級用數字表示,范圍從1~10。
- Thread.MIN_PRIORITY = 1;
- Thread.MAX_PRIORITY = 10;
- Thread.NORM_PRIORITY = 5;
-
使用以下方式改變或獲取優先級:
getPriority() //獲取優先級
setPriority(int xxx) //設置優先級
-
優先級的設定建議在start()調度前;
-
優先級低只是意味著獲得調度的 概率低,并不是優先級低就不會 被調用了,這都是看CPU的調度。
代碼示例:
/**
* @Description 測試線程的優先級
* @Author hzx
* @Date 2022-03-27
*/
public class TestPriority {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName()+"默認優先級-->"+Thread.currentThread().getPriority());
MyPriority myPriority = new MyPriority();
Thread t1 = new Thread(myPriority);
Thread t2 = new Thread(myPriority);
Thread t3 = new Thread(myPriority);
Thread t4 = new Thread(myPriority);
Thread t5 = new Thread(myPriority);
//先設置優先級,再啟動
t1.start(); //未設置,默認優先級
t2.setPriority(Thread.MIN_PRIORITY); //最小優先級 MIN_PRIORITY=1
t2.start();
t3.setPriority(Thread.MAX_PRIORITY); //最大優先級 MAX_PRIORITY=10
t3.start();
t4.setPriority(3);
t4.start();
t5.setPriority(8);
t5.start();
}
}
class MyPriority implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"線程優先級-->"+Thread.currentThread().getPriority());
}
}
執行結果:
main默認優先級-->5
Thread-0線程優先級-->5
Thread-1線程優先級-->1
Thread-4線程優先級-->8
Thread-2線程優先級-->10
Thread-3線程優先級-->3

浙公網安備 33010602011771號