next up previous
Next: 16.9 volatile Up: 16 スレッドのスケジューリング Previous: 16.7 ブロックの原因

16.8 優先順位

スレッドは,スレッドが行う処理の重要度を反映させるために ランタイムシステムが利用する優先順位(priority)を持つ. スレッドのスケジューリング保証は大変おおざっぱで, 優先順位の高いスレッドがブロック(実行可能ではない)された時だけ 低い優先順位のスレッドが動作する. しかし,低い優先順位のスレッドも,全く動作できないことがないように 優先順位エイジング(prioirty aging)と呼ばれる機能により動作する 場合もある. スレッドの優先順位は,そのスレッドを生成したスレッドの優先順位と最初は同 じになっている.優先順位はsetPriorityを用いて,Thread.MIN_PRIORITYと Thread.MAX_PRIORITYの定数の間の値に設定できる. スレッドに現在の値より低い優先順位を与えると,システムは他のスレッドを実 行させるかもしれない. スレッドの優先順位を返すメソッドとしてgetPriority()がある.

// priority.java

class Counter implements Runnable
{
    Thread thread;
    int counter = 0;
    volatile boolean goflag;

    public Counter(int p)
    {
        thread = new Thread(this);
        thread.setPriority(p);
    }

    public void start()
    {
        goflag = true;
        thread.start();
    }

    public void run()
    {
        while (goflag) counter++;
    }

    public void end() {
        goflag = false;
    }
}

class priority
{
    public static void main(String args[])
    {
        Counter thread1 =
            new Counter(Thread.NORM_PRIORITY + 2);
        Counter thread2 =
            new Counter(Thread.NORM_PRIORITY + 1);
        Counter thread3 =
            new Counter(Thread.NORM_PRIORITY - 1);
        Counter thread4 =
            new Counter(Thread.NORM_PRIORITY - 2);

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {}

        thread1.end();
        thread2.end();
        thread3.end();
        thread4.end();

        System.out.println(
            "Thread 1 counted: " + thread1.counter);
        System.out.println(
            "Thread 2 counted: " + thread2.counter);
        System.out.println(
            "Thread 3 counted: " + thread3.counter);
        System.out.println(
            "Thread 4 counted: " + thread4.counter);
    }
}


generated through LaTeX2HTML. M.Inaba 平成18年5月7日