Thread類代表了Java線程類,多個線程在排隊隊列等待執(zhí)行時機會是相等的,Thead類提供了setPriority(int priority)方法來設置線程對象的優(yōu)先級,參數(shù)是1-10之間的整數(shù),如果超過這個范圍則拋出非法參數(shù)異常:IllegalArgumentException。
Thread類提供了三個常量:
pubic static final intMAX_PRIORITY=10; ?代表最高優(yōu)先級
pubic static final intThread.MIN_PRIORITY=1 代表最低優(yōu)先級
pubic static final intThread.NORM_PRIORITY=5默認優(yōu)先級
Thread類對象的默認線程的優(yōu)先是5。
示例代碼:
classMyThreadextendsThread{
privateStringstr;
privateintcount;
publicMyThread(Stringstr,intcount){
this.str=str;
this.count=count;
}
@Override
publicvoidrun() {
for(inti=0;i
System.out.println(str);
}
}
publicclassDemo1 {
publicstaticvoidmain(String[]args) {
Threadt1=newMyThread("AAAAAAA",100);
Threadt2=newMyThread("BBBBBBB",100);
t1.setPriority(10);
t2.setPriority(1);
t1.start();
t2.start();
}
}
觀察運行結果可以發(fā)現(xiàn)t1線程優(yōu)先線t2結束。