Java Threads: Platform and Virtual Threads, Thread States and Interrupting (OCP 21)
Threads for the OCP 21 exam: processes, tasks and shared memory, platform versus virtual threads and carrier threads, creating threads with Thread.ofPlatform, Thread.ofVirtual and the constructor, start versus run, join, priorities, daemon threads, the six thread states and interrupting.
kvi5hnuCode Sprout team member9 min readOn this page
Waiting is everywhere in programs: for a disk, a network reply or a database. A program that does one thing at a time sits idle during every wait. Threads let a program do several things at once, so one task can run while another waits. Java 21 also introduced virtual threads, which make it practical to have hundreds of thousands of them. This article covers the thread basics the exam expects. The next articles add executors, thread safety and concurrent collections.
Vocabulary
| Term | Meaning |
|---|---|
| Thread | The smallest unit of execution that can be scheduled |
| Process | A group of threads running in one shared environment (one JVM) |
| Task | A single unit of work, such as a Runnable or Callable. A thread runs one task at a time, possibly many in turn. |
| Shared memory | Threads in a process share the heap: static fields, and any objects they all hold references to. Local variables belong to one thread. |
| System thread | Created by the JVM for its own work, for example garbage collection |
| User-defined thread | Created by your code |
| Platform thread | A thread mapped one-to-one onto an operating-system thread |
| Virtual thread | A lightweight thread managed by the JVM, run on a carrier thread when it has work to do |
| Carrier thread | A platform thread that the JVM uses to run virtual threads |
| Daemon thread | A thread that doesn't keep the JVM alive |
Concurrency means running several threads at the same time, or interleaved on fewer CPUs. A thread scheduler decides which threads run. When a thread's time slice ends before its work does, a context switch saves its state so that it can resume later. Switching costs time, so schedulers try to keep it to a minimum.
Platform threads and virtual threads
A platform thread is a thin wrapper around an operating-system thread. Each one reserves a large stack and kernel resources, so a JVM can typically sustain thousands of them, not millions. That's a fine fit for CPU-heavy work, but wasteful for tasks that spend most of their time waiting.
A virtual thread (final in Java 21, JEP 444) belongs to the JVM, not the operating system. While it runs, the JVM mounts it on a carrier thread, one of a small pool of platform threads. When it blocks, for example in Thread.sleep, on a socket or in a BlockingQueue, the JVM unmounts it and the carrier is free to run another virtual thread. When it's ready again, it may continue on a different carrier. Starting a million virtual threads that each sleep for a second works, while trying the same with platform threads typically fails with OutOfMemoryError: unable to create native thread.
Know these facts:
- Virtual threads help when there are many tasks that mostly wait (I/O). They don't make CPU-bound code faster.
- They're cheap, so don't pool them. Create a new one per task.
- They're always daemon threads, with a fixed priority of 5 (
Thread.NORM_PRIORITY). isVirtual()tells them apart. Virtual threads have an empty name unless you set one.
Creating and starting threads
A thread runs a task, usually a Runnable:
@FunctionalInterface
public interface Runnable {
void run();
}
| Code | Thread type |
|---|---|
Thread.ofPlatform().start(task) | platform (builder, Java 21) |
Thread.ofVirtual().start(task) | virtual (builder, Java 21) |
Thread.startVirtualThread(task) | virtual (shortcut) |
new Thread(task).start() | platform (classic constructor) |
Thread.ofVirtual().factory() | a ThreadFactory that creates virtual threads |
The builders make the thread type explicit, and they let you configure the thread before it starts:
Thread kitchen = Thread.ofPlatform()
.name("kitchen")
.priority(Thread.MAX_PRIORITY) // platform builder only
.daemon(true) // platform builder only
.unstarted(task); // created, not started
kitchen.start();
Thread waiter = Thread.ofVirtual()
.name("waiter-", 1) // waiter-1, waiter-2, ... for each thread built
.start(task); // created and started
start(task) creates and starts the thread. unstarted(task) only creates it, so you call start() later. The virtual builder (Thread.Builder.OfVirtual) has no priority() or daemon() methods, so calling them doesn't compile.
A class can also extend Thread and override run(), which you may see in older code. Passing a Runnable is preferred.
Order isn't guaranteed
Thread.ofPlatform().start(() -> System.out.print("Hello "));
System.out.print("World ");
This can print Hello World or World Hello . Once threads are started, their relative order is up to the scheduler. Within one thread, statements still run in order. The exam often asks which outputs are possible, so look for what's fixed (the order inside each thread) and what isn't (how the threads interleave).
join(): waiting for a thread
t.join() makes the current thread wait until t finishes. It throws the checked InterruptedException. There are also time-limited versions: join(long millis) and, since Java 19, join(Duration), which returns true if the thread finished. Starting threads and moving on is asynchronous. Waiting for a result before continuing is synchronous.
run() is not start()
Thread helper = Thread.ofPlatform().name("helper").unstarted(task);
helper.run(); // runs task in the CURRENT thread, like any method call
helper.start(); // runs task in a new thread named helper
helper.start(); // IllegalThreadStateException: a thread starts only once
Calling run() compiles and works, but no new thread is created. It's a classic exam trap.
Priorities
A priority from 1 (Thread.MIN_PRIORITY) to 10 (Thread.MAX_PRIORITY) is a hint to the scheduler. The default is 5 (Thread.NORM_PRIORITY). setPriority(11) throws IllegalArgumentException. Priorities never guarantee an order, and for virtual threads they're ignored: setPriority has no effect, and getPriority() always returns 5.
Daemon threads
The JVM exits when only daemon threads remain. A non-daemon thread keeps it alive even after main() returns:
Thread.ofPlatform().start(() -> {
sleepSeconds(10);
System.out.println("Worker done!"); // printed about 10 s later
});
System.out.println("main() returned");
With Thread.ofPlatform().daemon(true), only main() returned appears and the program ends. A thread inherits daemon status from the thread that creates it. Since main isn't a daemon, platform threads default to non-daemon. Change it with the builder's daemon(true) or with setDaemon(true) before starting. On a running thread, setDaemon throws IllegalThreadStateException. Virtual threads are always daemon, and setDaemon(false) on one throws IllegalArgumentException.
The thread life cycle
getState() returns one of six Thread.State values:

| State | Meaning |
|---|---|
NEW | created, start() not called yet |
RUNNABLE | running, or able to run when it gets a CPU |
BLOCKED | waiting to acquire a monitor lock (entering synchronized) |
WAITING | waiting with no time limit: join(), Object.wait(), LockSupport.park() |
TIMED_WAITING | waiting with a time limit: Thread.sleep(n), join(n), wait(n) |
TERMINATED | run() returned or threw an uncaught exception |
Threads in the three waiting states use no CPU. RUNNABLE doesn't mean the thread is executing right now, only that it could.
Interrupting a thread
t.interrupt() asks a thread to stop what it's doing. Nothing is forced. What happens depends on the thread:
- If it's sleeping or waiting (
sleep,join,wait...), the method throwsInterruptedException, and the interrupt flag is cleared. The thread goes back toRUNNABLEand runs its catch block. - If it's running, only the interrupt flag is set. The code has to check it:
while (!Thread.currentThread().isInterrupted()) {
// do a little work
}
| Method | Effect |
|---|---|
t.interrupt() | sets t's flag, or wakes it with InterruptedException |
t.isInterrupted() | reads the flag and leaves it unchanged |
Thread.interrupted() (static) | reads the current thread's flag and clears it |
So calling Thread.interrupted() twice in a row on an interrupted thread returns true, then false.
InterruptedException is checked. Don't swallow it silently in real code: either finish the task or restore the flag with Thread.currentThread().interrupt().
What's current, and what's obsolete
- Java 21: virtual threads,
Thread.ofPlatform(),Thread.ofVirtual(),Thread.Builder,Thread.startVirtualThread,isVirtual(). - Java 19+:
Thread.sleep(Duration),join(Duration), andthreadId(). The oldgetId()is deprecated. - Obsolete:
stop()always throwsUnsupportedOperationException(since Java 20).suspend()andresume()were disabled in Java 20 and removed in Java 23, so they don't even compile on Java 25. Never use them. Use interrupts instead. wait(),notify()andnotifyAll()still exist onObject, but they're beyond the exam. Prefer the Concurrency API.- Java 25 also finalized scoped values (JEP 506), a better alternative to
ThreadLocalfor virtual threads. Structured concurrency is still a preview feature. Neither is on the Java 21 exam.
Exam traps from this article
A complete example
The program creates threads three ways and prints their properties. It contrasts run() with start(), then drives a thread through every state, polling getState() so that the output is the same on every run. It interrupts both a sleeping thread and a busy one, starts ten thousand sleeping virtual threads, and finally compares daemon flags.
import java.time.Duration;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
public class Solution {
static String describe(Thread t) {
return String.format("%-9s virtual=%-5b daemon=%-5b priority=%-2d name='%s'",
t.getState(), t.isVirtual(), t.isDaemon(), t.getPriority(), t.getName());
}
// Waits (up to 5 s) until the thread reaches the given state, so the output is predictable.
static Thread.State awaitState(Thread t, Thread.State wanted) throws InterruptedException {
long end = System.nanoTime() + 5_000_000_000L;
while (t.getState() != wanted && System.nanoTime() < end) Thread.sleep(5);
return t.getState();
}
public static void main(String[] args) throws Exception {
Runnable task = () -> { };
System.out.println("== 1. Three ways to create a thread (not started yet)");
Thread built = Thread.ofPlatform().name("kitchen").priority(Thread.MAX_PRIORITY).unstarted(task);
Thread virtual = Thread.ofVirtual().name("waiter-", 1).unstarted(task);
Thread classic = new Thread(task);
for (Thread t : List.of(built, virtual, classic)) System.out.println(" " + describe(t));
virtual.setPriority(Thread.MIN_PRIORITY); // ignored for virtual threads
System.out.println(" virtual priority after setPriority(1): " + virtual.getPriority());
try {
virtual.setDaemon(false);
} catch (IllegalArgumentException e) {
System.out.println(" virtual.setDaemon(false) -> " + e.getClass().getSimpleName());
}
System.out.println("\n== 2. start() versus run()");
List<String> seen = Collections.synchronizedList(new ArrayList<>());
Runnable whoAmI = () -> seen.add(Thread.currentThread().getName());
Thread t1 = Thread.ofPlatform().name("helper").unstarted(whoAmI);
t1.run(); // plain method call on main
t1.start(); // a new thread
t1.join();
System.out.println(" run() then start(): " + seen);
try {
t1.start();
} catch (IllegalThreadStateException e) {
System.out.println(" second start() -> IllegalThreadStateException");
}
System.out.println("\n== 3. The six thread states");
Object lock = new Object();
Thread sleeper = Thread.ofPlatform().unstarted(() -> {
try { Thread.sleep(Duration.ofSeconds(30)); } catch (InterruptedException e) { /* woken */ }
});
System.out.println(" before start(): " + sleeper.getState());
sleeper.start();
System.out.println(" in Thread.sleep(): " + awaitState(sleeper, Thread.State.TIMED_WAITING));
Thread joiner = Thread.ofPlatform().start(() -> {
try { sleeper.join(); } catch (InterruptedException e) { /* ignore */ }
});
System.out.println(" in join() (no limit): " + awaitState(joiner, Thread.State.WAITING));
Thread blocked;
synchronized (lock) {
blocked = Thread.ofPlatform().start(() -> { synchronized (lock) { } });
System.out.println(" waiting for a lock: " + awaitState(blocked, Thread.State.BLOCKED));
}
System.out.println(" main thread itself: " + Thread.currentThread().getState());
sleeper.interrupt();
sleeper.join(); joiner.join(); blocked.join();
System.out.println(" after finishing: " + sleeper.getState());
System.out.println("\n== 4. Interrupting");
Thread napper = Thread.ofPlatform().start(() -> {
try {
Thread.sleep(Duration.ofSeconds(30));
} catch (InterruptedException e) {
System.out.println(" napper: InterruptedException, flag now "
+ Thread.currentThread().isInterrupted());
}
});
awaitState(napper, Thread.State.TIMED_WAITING);
napper.interrupt();
napper.join();
Thread worker = Thread.ofPlatform().start(() -> {
long loops = 0;
while (!Thread.currentThread().isInterrupted()) loops++;
System.out.println(" worker: saw the flag after " + (loops > 0 ? "some" : "no") + " loops, flag still "
+ Thread.currentThread().isInterrupted());
});
Thread.sleep(50);
worker.interrupt();
worker.join();
Thread.currentThread().interrupt();
System.out.println(" Thread.interrupted(): " + Thread.interrupted() + ", then " + Thread.interrupted());
System.out.println("\n== 5. Ten thousand virtual threads, each sleeping 200 ms");
AtomicInteger done = new AtomicInteger();
long start = System.nanoTime();
List<Thread> many = new ArrayList<>();
for (int i = 0; i < 10_000; i++) {
many.add(Thread.ofVirtual().start(() -> {
try { Thread.sleep(200); } catch (InterruptedException e) { return; }
done.incrementAndGet();
}));
}
for (Thread t : many) t.join();
long millis = (System.nanoTime() - start) / 1_000_000;
System.out.println(" finished: " + done.get() + ", took well under 10 s: " + (millis < 10_000));
System.out.println("\n== 6. Daemon threads");
Thread background = Thread.ofPlatform().daemon(true).unstarted(task);
System.out.println(" platform builder daemon(true): " + background.isDaemon());
System.out.println(" every virtual thread: " + Thread.ofVirtual().unstarted(task).isDaemon());
System.out.println(" main thread: " + Thread.currentThread().isDaemon());
}
}
Output:
== 1. Three ways to create a thread (not started yet)
NEW virtual=false daemon=false priority=10 name='kitchen'
NEW virtual=true daemon=true priority=5 name='waiter-1'
NEW virtual=false daemon=false priority=5 name='Thread-0'
virtual priority after setPriority(1): 5
virtual.setDaemon(false) -> IllegalArgumentException
== 2. start() versus run()
run() then start(): [main, helper]
second start() -> IllegalThreadStateException
== 3. The six thread states
before start(): NEW
in Thread.sleep(): TIMED_WAITING
in join() (no limit): WAITING
waiting for a lock: BLOCKED
main thread itself: RUNNABLE
after finishing: TERMINATED
== 4. Interrupting
napper: InterruptedException, flag now false
worker: saw the flag after some loops, flag still true
Thread.interrupted(): true, then false
== 5. Ten thousand virtual threads, each sleeping 200 ms
finished: 10000, took well under 10 s: true
== 6. Daemon threads
platform builder daemon(true): true
every virtual thread: true
main thread: false
Points to notice:
- Only the platform builder could set priority 10. The virtual thread kept priority 5 even after
setPriority(1), and refusedsetDaemon(false). run()recorded the namemain, andstart()recordedhelper. Then the secondstart()failed.sleepgaveTIMED_WAITING,join()gaveWAITING, and waiting for a heldsynchronizedlock gaveBLOCKED.- The sleeping thread got an
InterruptedException, with the flag already cleared. The busy thread had to pollisInterrupted(), and the flag stayed set. - Ten thousand virtual threads sleeping 200 ms each finished in a fraction of a second, because blocked virtual threads don't hold carrier threads.
Common questions
Should I replace all platform threads with virtual threads? No. They help with high numbers of mostly-waiting tasks. For a few CPU-heavy tasks, platform threads (usually through an executor) are just as good.
Does a higher priority run first? Not reliably. It's a hint that the scheduler may ignore, especially with free CPUs.
What happens to an exception thrown inside run()?
It ends that thread, which becomes TERMINATED, and is printed by the default uncaught-exception handler. It doesn't propagate to the thread that called start().
Summary
- Platform threads map to OS threads. Virtual threads are lightweight, run on carrier threads, and are always daemon with priority 5.
- Create threads with
Thread.ofPlatform(),Thread.ofVirtual(),Thread.startVirtualThread()ornew Thread(r). Callstart()once, neverrun(), to get a new thread. join()waits for a thread. The order between threads isn't guaranteed.- There are six states:
NEW,RUNNABLE,BLOCKED,WAITING,TIMED_WAITINGandTERMINATED. interrupt()wakes a waiting thread withInterruptedException, or sets the flag on a running one.Thread.interrupted()clears it.
Practice quiz
Test yourself with the threads quiz: 10 exam-style questions with explanations.
Previous: Java Named, Automatic and Unnamed Modules: Migration Strategies (OCP 21)
Next: Java ExecutorService: Runnable, Callable, Future, invokeAll and Scheduling (OCP 21)
Related reading
- Java Building Blocks: JDK, JVM, Class Structure and the main Method (OCP 21)
- Java try/catch: Chaining catch Blocks, Multi-catch and finally (OCP 21)
- Java Primitive Types, Literals, Wrapper Classes and Text Blocks (OCP 21)
- Writing a Class Loader and Bytecode Verification in Java
- Interruptible Sockets and TLS in Java: SocketChannel, Virtual Threads and SSLSocket

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.