Search code examples
javathread-priority

Java setPriority() what does it mean?


I'm confused by what Thread.setPriority does. Whatever priority I set, it does not matter, it still runs the program name first, then start.

Can someone please explain it to me what happens here?

class Main {
    public static void main(String[ ] args) {
        
        Name name = new Name();
        name.setPriority(2);
        
        Welcome welcome = new Welcome();
        welcome.setPriority(7);
        name.start();
        welcome.start();
    }
}

class Welcome extends Thread{
    public void run() {
        System.out.println("Welcome!");
    }
}

class Name extends Thread{
    public void run() {
        System.out.println("Please enter your name");
    }
}

Solution

  • Thread.setPriority does not set the execution order of threads, but helps the thread scheduler to decide which thread should be given priority when allocating the CPU.

    I think this answer explains it quite nicely:

    The method setPriority can be used to give the current thread object on which you are calling this method a priority. This priority is used by the thread scheduler of your OS to give the threads CPU time based on their priorities. So a thread with higher priority is more likely to get CPU time than one with a smaller priority.