線程優先級的理解


  1. package countPriority;
  2. /* 線程優先級用thread.setPriority(int a)( 1<=a<=10)方法來進行賦值
  3.  * 線程優先級有繼承性,如果主線程啟動threadA線程且threadA線程沒有另外賦予優先級,則threadA線程優先級和main線程一樣。優先級與執行順序無關
  4.  * CPU盡量將執行資源讓給線程優先級高的,即線程優先級高的總是會大部分先執行,但是不代表高優先級的線程全部都先執行完再執行低優先級的線程
  5.  * 優先級具有隨機性,優先級高的不一定每次都先執行
  6.  * 本例中用一個變量的自增量來判斷兩個優先級不同的線程運行時哪個占用CPU資源多*/
  7. public class ThreadA extends Thread {
  8.     private long count = 0;
  9.   public long getCount(){
  10.      return count;
  11.   }
  12.     public void run(){
  13.      while(true){
  14.       this.count++;
  15.     }
  16.   }
  17. }
  18. public class ThreadB extends Thread{
  19.   private long count = 0;
  20.   public long getCount(){
  21.     return count;
  22.   }
  23.   public void run(){
  24.     while(true){
  25.      this.count++;
  26.     }
  27.     }
  28. }
  29. public class Run {
  30.  public static void main(String[] args) {
  31.    // TODO Auto-generated method stub
  32.    try{
  33.       System.out.println("main優先級:"+Thread.currentThread().getPriority());//得到main線程的優先級
  34.       ThreadA threadA = new ThreadA();
  35.       threadA.setName("threadA");
  36.       threadA.setPriority(Thread.NORM_PRIORITY-3);//threadA線程的優先級為2
  37.       threadA.start();
  38.       ThreadB threadB = new ThreadB();
  39.       threadB.setName("threadB");
  40.       threadB.setPriority(Thread.NORM_PRIORITY+3);//threadB線程的優先級為8
  41.       threadB.start();
  42.       Thread.sleep(2000); //將主線程暫停2秒
  43.       threadA.stop();  //這里將線程強行停止,不建議使用stop()方法,該方法在JDK中被表明是“作廢/過期”的方法
  44.       threadB.stop();
  45.       System.out.println("a= "+threadA.getCount()); 
  46.       System.out.println("b= "+threadB.getCount());
  47.    }catch(InterruptedException ie){
  48.      ie.printStackTrace();
  49.    }
  50.   }
  51. }

運行結果如下圖

    輸出結果b>a說明了兩個線程在執行時threadB線程占用CPU的資源比threadA更多。雖然線程優先級高的占用CPU資源更多,但是並不意味着必須先將優先級高的運行完。由輸出結果很明顯看出線程threadB也在執行。

 


免責聲明!

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



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