設置和獲取線程優先級方法練習示例


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_PRIORITYMAX_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();

    }
}
 
        

 

 
        

 經過多次調用,可以看出優先級高的有較大幾率會優先運行

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM