Search code examples
javamultithreadingjava-7thread-priority

Why does the priority from getPriority inside a new thread differ from the priority in the calling thread?


For example, why does the following code not output a priority of 7?

public class Test {
    public static void main(String[] args) {
        Thread thread = new Thread(new A());
        thread.setPriority(7);
        System.out.println("in main: " + thread.getPriority());
        thread.start();
    }
}

class A extends Thread {
    @Override
    public void run() {
        System.out.println("in thread: " + this.getPriority());
    }
}

Output:

in main: 7
in thread: 5

Solution

  • new Thread(new A());
    

    You're treating the new A() as a Runnable and passing it to a separate Thread instance.

    The new Thread instance does not affect the Thread base of its Runnable at all.

    You should use new A() directly.