線程的優先級用數字來表示,默認范圍是1到10,即Thread.MIN_PRIORITY到Thread.MAX_PRIORTY.一個線程的默認優先級是5,即Thread.NORM_PRIORTY
對優先級操作的方法:
int getPriority():得到線程的優先級
void setPriority(int newPriority):當線程被創建後,可通過此方法改變線程的優先級
必須指出的是:線程的優先級無法保障線程的執行次序。只不過,優先級高的線程獲取CPU資源的概率較大。
class MyThread extends Thread{
String message;
MyThread(String message){
this.message=message;
}
public void run(){
for(int i=0;i<3;i++){
System.out.println(message+" "+getPriority());
}
}
}
public class PriorityThread{
public static void main(String args[]){
Thread t1=new MyThread("T1");
t1.setPriority(Thread.MIN_PRIORITY);
t1.start();
Thread t2=new MyThread("T2");
t2.setPriority(Thread.MAX_PRIORITY);
t2.start();
Thread t3=new MyThread("T3");
t3.setPriority(Thread.MAX_PRIORITY);
t3.start();
}
}