Javaスレッド(Thread)Thread優先順位

Thread優先順位

Javaスレッドでは、スレッドに優先順位を付与し、高い優先順位を持つスレッドに実行の優先権を与えて実行できます。

Threadクラス内部では、優先順位を決めるために次のような定数を提供しています。

    /**
     * The minimum priority that a thread can have.
     */
    public final static int MIN_PRIORITY = 1;

   /**
     * The default priority that is assigned to a thread.
     */
    public final static int NORM_PRIORITY = 5;

    /**
     * The maximum priority that a thread can have.
     */
    public final static int MAX_PRIORITY = 10;

最小1から最大10まで付与でき、デフォルトでは5が付与されます。

JVMでは、スレッドの実行が終わると、次に実行可能なスレッドの中から1つを選んで実行します。このとき優先順位が高いほど実行される確率が高くなります。優先順位が同じ場合は、スレッドスケジューラの基準によって実行されるスレッドが決定されます。

例1)Thread優先順位の設定

次の例では、2つのThreadに最上位と最下位の優先順位を設定しています。

package com.devkuma.tutorial.thread;

public class MyThreadPriority extends Thread {

    public MyThreadPriority(String name) {
        super(name);
    }

    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(super.getName() + " thread. i=" + i);
        }
    }

    public static void main(String[] args) {
        MyThreadPriority thread1 = new MyThreadPriority("first");
        MyThreadPriority thread2 = new MyThreadPriority("second");

        thread1.setPriority(Thread.MAX_PRIORITY);
        thread2.setPriority(Thread.MIN_PRIORITY);

        thread1.start();
        thread2.start();
    }
}

実行結果:

second thread. i=0
second thread. i=1
first thread. i=0
second thread. i=2
first thread. i=1
second thread. i=3
second thread. i=4
second thread. i=5
second thread. i=6
second thread. i=7
second thread. i=8
second thread. i=9
first thread. i=2
first thread. i=3
first thread. i=4
first thread. i=5
first thread. i=6
first thread. i=7
first thread. i=8
first thread. i=9

結果からわかるように、firstよりもsecondのほうが先に多く実行されたことを確認できます。