線程優先順序

每個線程都有一個優先順序。優先順序是由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.zaixian;

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

上一篇: 命名線程和當前線程 下一篇: Java守護線程