Search code examples
javamultithreadingjava-threads

What are the Conditions to Change Thread Priority while Running Thread in Java?


With This Code:

public static void main(String[] args) throws InterruptedException {
    MyThread testThread = new MyThread();

    System.out.println(testThread.getPriority());

    testThread.start();

    System.out.println(testThread.getPriority());
    testThread.setPriority(7);
    System.out.println(testThread.getPriority());
}

I get an Output where setPriority works as expected - the output is 5-5-7. But when commenting out the top getPriority as follows:

public static void main(String[] args) throws InterruptedException {
    MyThread testThread = new MyThread();

    //System.out.println(testThread.getPriority());

    testThread.start();

    System.out.println(testThread.getPriority());
    testThread.setPriority(7);
    System.out.println(testThread.getPriority());
}

The Priority doesn't change at all, I get an Output of 5-5. Why is that and what determines if the Thread Priority gets changed or not?


Solution

  • If you change the priority of a thread that has already run, it has no effect. For example:

        MyThread testThread = new MyThread();
        System.out.println(testThread.getPriority());
        testThread.start();
        // sleep for 1 second, making sure that testThread is done
        LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));
        // reports false
        System.out.println(testThread.isAlive());
        System.out.println(testThread.getPriority());
    
        testThread.setPriority(8);
        System.out.println(testThread.getPriority());
    

    Running this will reveal that testThread.setPriority(8); has no effect, the thread is not alive anymore.

    If we go to your example and add two statements:

        System.out.println(testThread.getPriority());
        System.out.println(testThread.isAlive());
        testThread.setPriority(7);
        System.out.println(testThread.isAlive());
        System.out.println(testThread.getPriority());
    

    and run the code with and without that System.out.println(testThread.getPriority()); - you will see that in one case (when that line is commented), the thread is not alive anymore (unlike when that line is not commented). Thus the expected result.