線程的優先級


            一、介紹       

   在Java中,每一個線程都有一個優先級,默認是一個線程繼承它的父線程的優先級。一個線程的默認優先級為NORM_PRIORITY = 5

  設置優先級的方法setPriority() ,可設置的值如下:  

1
2
3
static int MAX_PRIORITY = 10 ; //線程可以具有的最高優先級(執行概率最高)
static int MIN_PRIORITY = 1 ; //線程可以具有的最低優先級(執行概率最低)
static int NORM_PRIORITY = 5 //分配給線程的默認優先級

   線程的優先級:不是說哪個線程優先執行,如果設置某個線程的優先級高。那就是有可能被執行的概率高。並不是優先執行


 二、實例       

線程優先級實例代碼:這里設置線程1為最高優先級(被執行的概率高) 設置線程2為最低優先級

這里設置了線程1最高和線程2最低優先級后,並不是說線程1就優先執行等到線程1執行完才執行線程2。而是說線程1被執行的概率高。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
//線程類
public class PriorityThread implements Runnable{
     private boolean flag = true ;
     private int num= 0 ;
     @Override
     public void run() {
         while (flag){
             System.out.println(Thread.currentThread().getName()+ "-->" +num++);
         }
     }
     public void stop(){
         this .flag = ! this .flag;
     }
}
//測試線程優先級
public class PriorityDemo {
     public static void main(String[] args) throws InterruptedException {
         PriorityThread it1 = new PriorityThread();
         PriorityThread it2 = new PriorityThread();
         Thread proxy1 = new Thread(it1, "線程1" );
         Thread proxy2 = new Thread(it2, "線程2" );
         proxy1.setPriority(Thread.MAX_PRIORITY); //設置為最高優先級
         proxy2.setPriority(Thread.MIN_PRIORITY); //設置為最低優先級
         proxy1.start();
         proxy2.start();
         Thread.sleep( 1000 );
         it1.stop();
         it2.stop();
     }
}

執行結果如下:

線程1-->47755   統計共執行了4685次

線程2-->19211   統計共執行了1469次


 三、總結       

1、每個線程都有一個默認的優先級,默認情況下是NORM_PRIORITY = 5

2、線程的優先級表示的是被執行的概率,並不是絕對的優先執行。

3、設置線程優先級的方法setPriority(Thread.MAX_PRIORITY);








免責聲明!

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



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