Java多執行緒(三)
阿新 • • 發佈:2021-10-02
四.執行緒優先順序
java提供一個執行緒排程器監控程式中啟動後進入就緒狀態的所有執行緒,排程器按照優先順序決定執行緒執行順序。(優先順序只表示獲得排程的概率,並不是優先順序低的不被呼叫,最終還是取決於CPU的排程)
優先順序用數字表示,1~10,預設為5。
- Thread.MIN_PRIORITY = 1
- Thread.MAX_PRIORITY = 10
- Thread.NORM_PRIORITY = 5
通過get.Priority(),setPriority()獲取和設定優先順序。
public class Priority implements Runnable{ @Override public void run() { System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority()); } public static void main(String[] args) { System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority()); Priority p = new Priority(); Thread a = new Thread(p); Thread b = new Thread(p); Thread c = new Thread(p); Thread d = new Thread(p); Thread e = new Thread(p); Thread f = new Thread(p); a.setPriority(Thread.MIN_PRIORITY); a.start(); b.setPriority(7); b.start(); c.setPriority(Thread.MAX_PRIORITY); c.start(); d.setPriority(2); d.start(); e.setPriority(Thread.NORM_PRIORITY); e.start(); f.setPriority(9); f.start(); } }
點選檢視執行結果
main-->5
Thread-2-->10
Thread-5-->9
Thread-1-->7
Thread-4-->5
Thread-3-->2
Thread-0-->1