Cyh的博客

          Email:kissyan4916@163.com
          posts - 26, comments - 19, trackbacks - 0, articles - 220

          線程6--線程優先級

          Posted on 2009-06-02 20:45 啥都寫點 閱讀(200) 評論(0)  編輯  收藏 所屬分類: J2SE
          關鍵技術:
          • Java線程的優先級分為10個級別,數字越大,級別越高,默認為5。
          • Thread的setPriority實例方法為線程設置優先級,參數為int類型。
          • 對于兩個同時啟動的線程,大多數情況下優先級高的線程會比優先級低的線程先運行,當也有例外情況,完全取決于Java虛擬機的調度。

          package book.thread;


          public class Priority {
              
              
          static class MyThread extends Thread{
                  
          private int ID = 0;
                  
          public MyThread(int id){
                      
          this.ID = id;
                  }
                  
          public void run(){
                      System.out.println(
          "MyThread-" + this.ID + 
                              
          " begin! Priority: " + this.getPriority());

                      System.out.println(
          "MyThread-" + this.ID + " end!");
                  }
              }

              
          public static void main(String[] args) {
                  
          //建立3個優先級不同的線程
                  MyThread[] myThreads = new MyThread[3];
                  
          for (int i=0; i<3; i++){
                      myThreads[i] 
          = new MyThread(i+1);
                      
          //三個線程的優先級分別是1,4,7
                      myThreads[i].setPriority(i*3+1);
                  }
                  
          //按優先級從低到高啟動線程
                  for (int i=0; i<3; i++){
                      myThreads[i].start();
                  }
                  
          //先啟動的線程不一定先運行,虛擬機會考慮線程的優先級,同等情況下,優先級高的線程先運行
              }
          }



                                                                                                                 --    學海無涯
                  

          主站蜘蛛池模板: 永安市| 饶阳县| 湖口县| 乐平市| 水城县| 巫溪县| 岳阳市| 兴城市| 宜兰县| 屯昌县| 根河市| 岗巴县| 冷水江市| 库尔勒市| 金寨县| 北流市| 宝鸡市| 乌审旗| 汝城县| 宜城市| 彰化市| 绥江县| 泾川县| 伊宁县| 巴马| 子长县| 离岛区| 衡阳市| 宜丰县| 蓬莱市| 开原市| 金塔县| 博罗县| 大田县| 蛟河市| 拉萨市| 临汾市| 贵阳市| 清水河县| 胶州市| 达日县|