Does the higher priority thread get the same CPU as the lower priority?

Below 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 set a higher priority for A, I expected the print statement to give a higher value for A, but this is not the case. Below is an example of the 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 started the program using the command

taskset 0x00000001 java -jar Untitled.jar

      

and verified with the performance monitor UI that only one processor is in use (if I execute a command java -jar Untitled.jar

, two processors are used).

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

+3


source to share


1 answer


Your program is fine.

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



You can see the difference if this program is run under different circumstances (CPU load) or on a different platform (but the expected results may be consistent).

Note. On Linux systems, thread priorities are not considered by default. You must use a parameter XX:ThreadPriorityPolicy

to enable thread priority on Linux,

+6


source







All Articles