java中,線程優先級有1~10,10個級別。設置優先級小於1或大於10,拋出異常IllegalArgumentException()。
setPriority() 設置線程優先級
優先級常量
public final static int MIN_PRIORITY=1;
public final static int NORM_PRIORITY=5;
public final static int MAX_PRIORITY=10;
線程優先級的特點:
1 繼承性 :線程t1中啟動線程t2,則默認線程t2優先級與t1相同。
2 規則性 :系統資源盡量先分配給優先級高的,優先級高的線程先執行完的可能性大
3 隨機性 :優先級的高的不一定先執行完,資源的分配不是嚴格按照優先級分配的,因此具有隨機性。
另外,線程執行速度,與代碼的編寫順序無關。不一定先啟動的就先執行完。
示例:
package threadTest7;
public class MyThread1 extends Thread{
@Override
public void run() {
System.out.println("MyThread1 run priority= " + this.getPriority());
MyThread2 thread2= new MyThread2();
thread2.start();
}
}
package threadTest7;
public class MyThread2 extends Thread{
@Override
public void run() {
System.out.println("MyThread2 run priority= " + this.getPriority());
}
}
package threadTest7;
public class Run {
public static void main(String[] args){
System.out.println("main Thread begin priority= " + Thread.currentThread().getPriority());
// Thread.currentThread().setPriority(11);
Thread.currentThread().setPriority(7);
System.out.println("main Thread end priority= " + Thread.currentThread().getPriority());
MyThread1 thread1 = new MyThread1();
thread1.start();
}
}
結果:
main Thread begin priority= 5
main Thread end priority= 7
MyThread1 run priority= 7
MyThread2 run priority= 7
《Java多線程編程核心技術》 高洪岩