Search code examples
javamultithreadingconcurrencythread-priority

Higher priority thread getting the same CPU amount as the lower priority?


Following is my code.

public class Test {
    public static void main(String[] args) throws InterruptedException {
        PrintingThread a = new PrintingThread("A");
        a.setPriority(9);
        PrintingThread b = new PrintingThread("B");
        b.setPriority(1);
        a.start();
        b.start();
    }

    static class PrintingThread extends Thread {
        private int i = 0;
        private String name;

        public PrintingThread(String name) {
            super();
            this.name = name;
        }

        @Override
        public void run() {
            while (true) {
                i++;
                if (i % 100000 == 0) {
                    System.out.println("Thread " + name + " count=" + i
                            + ". Time :" + System.currentTimeMillis());
                }
            }

        }
    }
}

Since I have set a higher priority to A, I expected that the print statement would give a higher value for A, but this is not the case. Following is a sample output after running the program for a while.

Thread A count=1033300000. Time :1431937330486
Thread A count=1033400000. Time :1431937330486
Thread A count=1033500000. Time :1431937330486
Thread A count=1033600000. Time :1431937330486
Thread B count=1058600000. Time :1431937330485
Thread B count=1058700000. Time :1431937330487

I am on Ubuntu and running Java version 1.7.0-79-b15. I ran the program using the command

taskset 0x00000001 java -jar Untitled.jar

and have verified using the System Monitor UI that only one CPU is being used(if I execute the command java -jar Untitled.jar two CPUs are used).

Does this mean that there is no difference even if I set the priority? Or is there something wrong with my program?


Solution

  • Your program is fine.

    Setting priority of threads is just a hint to the underlying OS (from your code) asking it to try and increase the priority of the thread. There is no guarantee (it is not even necessary) that the OS will do something based on your call.

    You could see a difference if this program is run under different circumstances (CPU load) or different platform (but expected results might not be consistent).

    Note : On Linux systems, thread priorities are not considered by default. You have to use XX:ThreadPriorityPolicy option to enable thread priority on Linux,