Java Thread Priority

Su Suriya Ravichandran Updated 18 Nov 2026
8 min read ·Lesson 188 of 306

Java thread priority is a number from 1 to 10 that tells the thread scheduler how important a thread is. A higher number suggests that the thread should get CPU time before threads with a lower number.

Priorities let you mark background work (cleanup, logging, reports) as less important than user-facing work (handling requests, payments). This lesson shows how to read and set priorities, how they are inherited and limited, and why you must never rely on them for correctness.


Java Thread Priority Constants

The Thread class defines three constants for the priority range. Every new thread starts with the priority of the thread that created it, which for code started from main is NORM_PRIORITY.

ConstantValueMeaning
Thread.MIN_PRIORITY1Lowest priority
Thread.NORM_PRIORITY5Default priority
Thread.MAX_PRIORITY10Highest priority
public class PriorityBasics {
    public static void main(String[] args) {
        System.out.println("MIN_PRIORITY  = " + Thread.MIN_PRIORITY);
        System.out.println("NORM_PRIORITY = " + Thread.NORM_PRIORITY);
        System.out.println("MAX_PRIORITY  = " + Thread.MAX_PRIORITY);

        Thread mainThread = Thread.currentThread();
        System.out.println("main priority = " + mainThread.getPriority());

        Thread worker = new Thread(() -> { }, "worker");
        System.out.println("worker priority (default) = " + worker.getPriority());
    }
}

Output:

MIN_PRIORITY  = 1
NORM_PRIORITY = 5
MAX_PRIORITY  = 10
main priority = 5
worker priority (default) = 5

How it works:

  • getPriority() returns a thread's current priority as an int.
  • The main thread runs at priority 5, and worker is created by main, so it also starts at 5.

How to Set Thread Priority in Java

Call setPriority(int) to change a thread's priority. You can call it before or after start(), but setting it before starting is the usual practice.

thread.setPriority(int newPriority)   // 1 (MIN) to 10 (MAX)
int priority = thread.getPriority();
public class SetPriority {
    public static void main(String[] args) throws InterruptedException {
        Thread emailSender = new Thread(() ->
                System.out.println(Thread.currentThread().getName()
                        + " running with priority " + Thread.currentThread().getPriority()),
                "email-sender");
        Thread paymentHandler = new Thread(() ->
                System.out.println(Thread.currentThread().getName()
                        + " running with priority " + Thread.currentThread().getPriority()),
                "payment-handler");

        emailSender.setPriority(Thread.MIN_PRIORITY);     // 1: background work
        paymentHandler.setPriority(Thread.MAX_PRIORITY);  // 10: important work

        emailSender.start();
        emailSender.join();
        paymentHandler.start();
        paymentHandler.join();
    }
}

Output:

email-sender running with priority 1
payment-handler running with priority 10

How it works:

  • The email sender is background work, so it gets MIN_PRIORITY.
  • The payment handler is important, so it gets MAX_PRIORITY.
  • Inside run(), Thread.currentThread().getPriority() reads the priority of the running thread. Named threads like these are explained in Java Thread Class.

Invalid Priority Values

Any value outside 1 to 10 is rejected with an IllegalArgumentException.

public class InvalidPriority {
    public static void main(String[] args) {
        Thread worker = new Thread(() -> { }, "worker");
        int[] attempts = {0, 7, 11};

        for (int priority : attempts) {
            try {
                worker.setPriority(priority);
                System.out.println("setPriority(" + priority + ") OK -> " + worker.getPriority());
            } catch (IllegalArgumentException e) {
                System.out.println("setPriority(" + priority + ") failed: " + e.getClass().getSimpleName());
            }
        }
    }
}

Output:

setPriority(0) failed: IllegalArgumentException
setPriority(7) OK -> 7
setPriority(11) failed: IllegalArgumentException

How it works:

  • 0 and 11 are outside the allowed range, so setPriority() throws and the priority stays unchanged.
  • 7 is valid and is stored. Any value from 1 to 10 is allowed, not just the three constants.

Thread Priority Is Inherited

A new thread copies the priority of the thread that creates it. This matters when a high- or low-priority thread starts helper threads.

public class InheritPriority {
    public static void main(String[] args) throws InterruptedException {
        Thread parent = new Thread(() -> {
            Thread self = Thread.currentThread();
            System.out.println("parent priority: " + self.getPriority());

            // A thread created inside "parent" copies parent's priority
            Thread child = new Thread(() -> { }, "child");
            System.out.println("child priority : " + child.getPriority());

            child.setPriority(Thread.NORM_PRIORITY); // can still be changed
            System.out.println("child after set: " + child.getPriority());
        }, "parent");

        parent.setPriority(8);
        parent.start();
        parent.join();
    }
}

Output:

parent priority: 8
child priority : 8
child after set: 5

How it works:

  • parent runs at priority 8. The child thread is created inside parent's run() method, so it starts at 8 too.
  • The child's priority can still be changed with setPriority() before it starts.

Thread Group Maximum Priority

Every platform thread belongs to a ThreadGroup. A group can set a maximum priority; a thread in that group can never go above it, even if you ask for more.

public class GroupLimit {
    public static void main(String[] args) {
        ThreadGroup batchJobs = new ThreadGroup("batch-jobs");
        batchJobs.setMaxPriority(4); // no thread in this group may go above 4

        Thread importer = new Thread(batchJobs, () -> { }, "importer");
        importer.setPriority(Thread.MAX_PRIORITY); // asks for 10...

        System.out.println("group max priority  : " + batchJobs.getMaxPriority());
        System.out.println("importer priority   : " + importer.getPriority()); // ...gets 4
    }
}

Output:

group max priority  : 4
importer priority   : 4

How it works:

  • setMaxPriority(4) caps every thread in batch-jobs at 4.
  • importer.setPriority(10) does not throw; Java silently uses the smaller value, 4.

Note: Thread groups are a legacy feature and are rarely used in new code. They are shown here because the cap explains why setPriority() sometimes seems to "not work".


Java Thread Priority Is Only a Hint

Priorities are passed to the operating system as a hint. How much they matter depends on the OS, the JVM settings and how many CPU cores are free. On Linux, the JVM ignores Java priorities by default; on Windows they are mapped to OS priorities but still give no guarantee.

import java.util.concurrent.atomic.AtomicBoolean;

public class PriorityRace {
    public static void main(String[] args) throws InterruptedException {
        AtomicBoolean running = new AtomicBoolean(true);
        long[] counts = new long[2];

        Thread low = new Thread(() -> {
            while (running.get()) counts[0]++;
        }, "low");
        Thread high = new Thread(() -> {
            while (running.get()) counts[1]++;
        }, "high");

        low.setPriority(Thread.MIN_PRIORITY);
        high.setPriority(Thread.MAX_PRIORITY);

        low.start();
        high.start();
        Thread.sleep(1000); // let both threads count for one second
        running.set(false);
        low.join();
        high.join();

        System.out.println("CPU cores available: " + Runtime.getRuntime().availableProcessors());
        System.out.printf("low  (priority 1)  counted %,d%n", counts[0]);
        System.out.printf("high (priority 10) counted %,d%n", counts[1]);
    }
}

Output of two runs on the same 2-core Linux machine (your numbers will differ):

CPU cores available: 2
low  (priority 1)  counted 390,533,135
high (priority 10) counted 739,973,897
CPU cores available: 2
low  (priority 1)  counted 1,204,851,716
high (priority 10) counted 1,189,102,012

How it works:

  • Both threads count as fast as they can for one second. If priorities were strict, high would always count far more than low.
  • In the first run high happened to count more; in the second run low won. The difference comes from scheduling noise, not from the priorities.
  • With at least as many cores as busy threads, each thread gets its own core anyway, so priorities make little difference.

Note: Never use priorities to make a program correct, for example to make sure one thread runs before another. Use Java Thread Join, locks, or other coordination tools for that. Priorities can only influence performance, and only on some systems.

StatementTrue?
A higher-priority thread runs firstNot guaranteed
A low-priority thread may never run (starvation)Possible on some systems
Priorities behave the same on every OSNo
Priority affects which thread gets a lockNo
setPriority() above the group maximum throwsNo, the value is lowered silently

Thread Priority with Virtual Threads and Thread Builders

Virtual threads (Java 21) always have priority NORM_PRIORITY, and setPriority() has no effect on them. Platform threads created with the Thread.ofPlatform() builder can set their priority directly.

public class VirtualPriority {
    public static void main(String[] args) throws InterruptedException {
        Thread virtual = Thread.ofVirtual().name("virtual-worker").unstarted(() -> { });
        virtual.setPriority(Thread.MAX_PRIORITY); // ignored for virtual threads

        Thread platform = Thread.ofPlatform().name("platform-worker")
                .priority(Thread.MAX_PRIORITY)   // builders can set priority too
                .unstarted(() -> { });

        System.out.println("virtual  priority: " + virtual.getPriority());
        System.out.println("platform priority: " + platform.getPriority());
    }
}

Output:

virtual  priority: 5
platform priority: 10

How it works:

  • Thread.ofVirtual() creates a virtual thread. Calling setPriority(MAX_PRIORITY) is silently ignored, so it stays at 5.
  • Thread.ofPlatform().priority(...) sets the priority while building the thread, before it is started. The builder methods are an alternative to new Thread(...), as shown in Create a Thread in Java.

Real-World Example: Thread Pools with Different Priorities

In a shop backend, checkout requests should be favoured over maintenance jobs like rebuilding a search index. Thread pools create their own threads, so you give them a ThreadFactory that sets the priority on every new thread.

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class PriorityThreadFactoryDemo {

    // Creates named platform threads that all share one priority
    static ThreadFactory factory(String poolName, int priority) {
        AtomicInteger counter = new AtomicInteger(1);
        return task -> {
            Thread t = new Thread(task, poolName + "-" + counter.getAndIncrement());
            t.setPriority(priority);
            t.setDaemon(true); // background pools should not keep the JVM alive
            return t;
        };
    }

    static String describe(String job) {
        Thread t = Thread.currentThread();
        return String.format("%-20s on %-13s priority %d", job, t.getName(), t.getPriority());
    }

    public static void main(String[] args) throws Exception {
        ExecutorService checkoutPool =
                Executors.newFixedThreadPool(2, factory("checkout", Thread.MAX_PRIORITY - 2));
        ExecutorService maintenancePool =
                Executors.newFixedThreadPool(1, factory("maintenance", Thread.MIN_PRIORITY));

        List<Future<String>> results = new ArrayList<>();
        results.add(checkoutPool.submit(() -> describe("place order #501")));
        results.add(checkoutPool.submit(() -> describe("place order #502")));
        results.add(maintenancePool.submit(() -> describe("rebuild search index")));
        results.add(maintenancePool.submit(() -> describe("compress old logs")));

        for (Future<String> result : results) {
            System.out.println(result.get());
        }

        checkoutPool.shutdown();
        maintenancePool.shutdown();
    }
}

Output:

place order #501     on checkout-1    priority 8
place order #502     on checkout-2    priority 8
rebuild search index on maintenance-1 priority 1
compress old logs    on maintenance-1 priority 1

How it works:

  1. A reusable factory. factory(poolName, priority) returns a ThreadFactory lambda. For each new thread it sets a readable name (checkout-1, checkout-2, ...), the priority, and daemon mode.
  2. Two pools. checkoutPool uses priority 8 for customer-facing work; maintenancePool uses MIN_PRIORITY for background jobs. Both are created with Executors.newFixedThreadPool(size, factory).
  3. Submitting work. Each task returns a description of the thread it ran on. Future.get() waits for each result in order.
  4. What the output proves. Checkout tasks run on checkout-* threads with priority 8; maintenance tasks share the single maintenance-1 thread with priority 1.
  5. Realistic expectations. On a busy Windows server, the OS may give the checkout threads more CPU time. On Linux, the priorities are ignored by default, so the real protection is the separate pools: maintenance work can never use more than one thread. Thread pools are covered in detail in the Executor Service and Thread Pools lessons.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Thread Priority and get answers drawn from it.

Signed-in readers only.