線程優先級

每個線程都有一個優先級。優先級是由110之間的數字表示。在大多數情況下,線程調度程序根據線程的優先級(稱爲搶佔式調度)來調度線程。 但它不能保證,因爲它依賴於JVM規範,它選擇哪種調度。

Thread類中定義的3個常量:

  • public static int MIN_PRIORITY
  • public static int NORM_PRIORITY
  • public static int MAX_PRIORITY

線程的默認優先級爲5(NORM_PRIORITY)。 MIN_PRIORITY的值爲1MAX_PRIORITY的值爲10

線程優先級示例:

package com.yiibai;

class TestMultiPriority1 extends Thread {
    public void run() {
        System.out.println("running thread name is:" + Thread.currentThread().getName());
        System.out.println("running thread priority is:" + Thread.currentThread().getPriority());

    }

    public static void main(String args[]) {
        TestMultiPriority1 m1 = new TestMultiPriority1();
        TestMultiPriority1 m2 = new TestMultiPriority1();
        m1.setPriority(Thread.MIN_PRIORITY);
        m2.setPriority(Thread.MAX_PRIORITY);
        m1.start();
        m2.start();

    }
}

執行上面示例代碼,得到以下結果:

running thread name is:Thread-0
running thread name is:Thread-1
running thread priority is:1
running thread priority is:10