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();
}
//先啟動的線程不一定先運行,虛擬機會考慮線程的優先級,同等情況下,優先級高的線程先運行
}
}
--
學海無涯