天天看點

多線程——線程優先級

目錄

1、線程優先級具有繼承性

2、線程優先級的作用

Thread類源碼中定義:

最低優先級為1
public final static int MIN_PRIORITY = 1;

一般沒有繼承,沒有顯示指定優先級時,預設優先級為5
public final static int NORM_PRIORITY = 5;

最高優先級為10
public final static int MAX_PRIORITY = 10;
           

1、線程優先級具有繼承性

當線程A啟動B線程的時候,B線程相當于子線程,A為父線程,那麼B線程會繼承A的優先級,A優先級=B優先級。如果不想繼承優先級,可以設定優先級,setPriority();

class A extends Thread{

    @Override

    public void run(){

        B b = new B(); //建立對象的時候,就已經将b線程的優先級設為A的優先級了。

        b.start(); //隻是啟動而已

    }

}

class B extends Thread{ }

2、線程優先級的作用

優先級越高的線程,CPU越是盡量将資源給這個線程,但是并不代表優先級高,就要等着把優先級高的線程執行完了才會去執行優先級低的線程,不是這樣的,隻是說CPU會盡量執行高優先級線程,低優先級線程也有機會得到執行,隻是機會少一些。

假如兩個線程,優先級相差越大,這種被執行的差距就越大,優先級相差小的時候,這種被執行的差距就小一些。

舉個例子說明:

 下面有兩個内容一樣的線程,隻是優先級設定不一樣,一個是1,一個是9.

public class LowThread extends Thread {
    private int count = 0;
    public int getCount(){
        return count;
    }
    @Override
    public void run(){
        while (true){
            count++;
        }
    }
}

public class HighThread extends Thread {
    private int count = 0;
    public int getCount(){
        return count;
    }
    @Override
    public void run(){
        while (true){
            count++;

        }
    }
}

public static void main(String[] args) throws InterruptedException {
            LowThread lowThread = new LowThread();
            HighThread highThread = new HighThread();
            highThread.setPriority(8);
            lowThread.setPriority(1);
            lowThread.start();

            highThread.start();
            Thread.sleep(1000);
            lowThread.stop();
            highThread.stop();
            System.out.println("lowThread:"+ lowThread.getCount());
            System.out.println("highThread:"+ highThread.getCount());
        }
           

這個線程的運作時在電腦比較閑的情況下測試的,測試了好多次,9級線程的count總是大于1級線程的count。

說明:高優先級線程被運作的時間總是大于低優先級的線程,就是優先級高,被運作的機會大。

多線程——線程優先級

繼續閱讀