int getPriority() 返回此線程的優先級。
public class MyThreadDemo { public static void main(String[] args) { MyThread mt1 = new MyThread(); MyThread mt2 = new MyThread(); MyThread mt3 = new MyThread(); mt1.setName("飛機"); mt2.setName("高鐵"); mt3.setName("汽車");
System.out.println(mt1.getPriority()); System.out.println(mt2.getPriority()); System.out.println(mt3.getPriority()); } }
運行結果可以得出,線程默認的優先級是:5
//void setPriority(int newPriority) 更改此線程的優先級。
把優先級設置成100時會發生異常:IllegalArgumentException,此異常 如果優先級不在MIN_PRIORITY
到MAX_PRIORITY
時會發生,所以此時來獲取這兩個值的范圍是多少
public static void main(String[] args) { System.out.println(Thread.MIN_PRIORITY); System.out.println(Thread.NORM_PRIORITY); System.out.println(Thread.MAX_PRIORITY); }
最小值為:1 最大值為:10 默認值為:5
public class MyThreadDemo { public static void main(String[] args) { MyThread mt1 = new MyThread(); MyThread mt2 = new MyThread(); MyThread mt3 = new MyThread(); mt1.setName("飛機"); mt2.setName("高鐵"); mt3.setName("汽車"); //void setPriority(int newPriority) 更改此線程的優先級。 mt1.setPriority(10); mt2.setPriority(5); mt3.setPriority(1); mt1.start(); mt2.start(); mt3.start(); } }
經過多次調用,可以看出優先級高的有較大幾率會優先運行