- package countPriority;
- /* 線程優先級用thread.setPriority(int a)( 1<=a<=10)方法來進行賦值
- * 線程優先級有繼承性,如果主線程啟動threadA線程且threadA線程沒有另外賦予優先級,則threadA線程優先級和main線程一樣。優先級與執行順序無關
- * CPU盡量將執行資源讓給線程優先級高的,即線程優先級高的總是會大部分先執行,但是不代表高優先級的線程全部都先執行完再執行低優先級的線程
- * 優先級具有隨機性,優先級高的不一定每次都先執行
- * 本例中用一個變量的自增量來判斷兩個優先級不同的線程運行時哪個占用CPU資源多*/
- public class ThreadA extends Thread {
- private long count = 0;
- public long getCount(){
- return count;
- }
- public void run(){
- while(true){
- this.count++;
- }
- }
- }
- public class ThreadB extends Thread{
- private long count = 0;
- public long getCount(){
- return count;
- }
- public void run(){
- while(true){
- this.count++;
- }
- }
- }
- public class Run {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- try{
- System.out.println("main優先級:"+Thread.currentThread().getPriority());//得到main線程的優先級
- ThreadA threadA = new ThreadA();
- threadA.setName("threadA");
- threadA.setPriority(Thread.NORM_PRIORITY-3);//threadA線程的優先級為2
- threadA.start();
- ThreadB threadB = new ThreadB();
- threadB.setName("threadB");
- threadB.setPriority(Thread.NORM_PRIORITY+3);//threadB線程的優先級為8
- threadB.start();
- Thread.sleep(2000); //將主線程暫停2秒
- threadA.stop(); //這里將線程強行停止,不建議使用stop()方法,該方法在JDK中被表明是“作廢/過期”的方法
- threadB.stop();
- System.out.println("a= "+threadA.getCount());
- System.out.println("b= "+threadB.getCount());
- }catch(InterruptedException ie){
- ie.printStackTrace();
- }
- }
- }
運行結果如下圖

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