Course contentsShow
← Java
Lesson 2627 of 2,87048. Concurrency FundamentalsFree lesson

Setting and Getting Thread Priority

Use setPriority() and getPriority() methods to control and inspect thread priority values at runtime.

Setting and Getting Thread Priority

What you'll learn: How to use setPriority() and getPriority() methods to control and inspect thread priority values at runtime.

Controlling Priority at Runtime

Now that you understand priority levels exist, you need to know how to actually assign and check them. Java's Thread class provides two straightforward methods: setPriority(int priority) sets a thread's priority, and getPriority() retrieves its current priority value.

The setPriority Method

You can change a thread's priority by calling setPriority() with an integer between Thread.MIN_PRIORITY (1) and Thread.MAX_PRIORITY (10):

Thread worker = new Thread(() -> {
    System.out.println("Working...");
});

worker.setPriority(Thread.MAX_PRIORITY); // Set to 10
worker.start();

Think of this like setting the urgency level on a task management app—you're telling the scheduler how important this thread is compared to others.

The getPriority Method

To inspect a thread's current priority, use getPriority():

Thread worker = new Thread(() -> {
    System.out.println("Priority: " + Thread.currentThread().getPriority());
});

worker.setPriority(8);
System.out.println("Before start: " + worker.getPriority()); // 8
worker.start();

Practical Example

Thread low = new Thread(() -> System.out.println("Low priority task"));
Thread high = new Thread(() -> System.out.println("High priority task"));

low.setPriority(Thread.MIN_PRIORITY);  // 1
high.setPriority(Thread.MAX_PRIORITY); // 10

System.out.println("Low: " + low.getPriority());   // 1
System.out.println("High: " + high.getPriority()); // 10

high.start();
low.start();

Important Timing Note

You can call setPriority() before or after starting a thread, but setting it before start() is clearer and prevents race conditions.

Key Takeaway: Use setPriority(int) to assign priority values (1-10) and getPriority() to read them, allowing runtime control over thread scheduling hints.