Java Thread Class
The Java Thread class (java.lang.Thread) represents one thread of execution. Every thread you create, and the main thread itself, is a Thread object. Its methods let you name a thread, check whether it is still running, make it a background thread, ask it to stop, and handle errors it throws.
This lesson walks through the constructors and the most important methods of the Thread class, each with a runnable example. Thread is in java.lang, so no import is needed.
Java Thread Class Constructors
A Thread can be created with or without a task (a Runnable) and with or without a name. A thread without a name gets a default one: Thread-0, Thread-1, and so on.
| Constructor | Creates |
|---|---|
Thread() | A thread with no task and a default name |
Thread(Runnable task) | A thread that runs task, default name |
Thread(Runnable task, String name) | A thread that runs task, with a name |
Thread(String name) | A named thread with no task (used when subclassing) |
public class ConstructorsDemo {
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> System.out.println(" running on " + Thread.currentThread().getName());
Thread noArgs = new Thread(); // no task, default name
Thread withTask = new Thread(task); // task, default name
Thread withName = new Thread(task, "invoice-printer"); // task and name
Thread onlyName = new Thread("idle-thread"); // name, no task
for (Thread t : new Thread[] {noArgs, withTask, withName, onlyName}) {
System.out.println(t.getName() + ":");
t.start();
t.join(); // a thread without a task simply ends immediately
}
}
}
Output:
Thread-0:
Thread-1:
running on Thread-1
invoice-printer:
running on invoice-printer
idle-thread:
How it works:
Thread-0andidle-threadhave no task. Theirrun()method is empty, so they start and end without printing anything.Thread-1andinvoice-printerrun the sharedtask, which prints the name of the thread running it.- Default names are numbered in creation order across the whole program, so they are not very useful in logs. Give important threads a meaningful name.
Note: The Create a Thread in Java lesson shows the other ways to create threads, including the Java 21
Thread.ofPlatform()andThread.ofVirtual()builders.
Thread Names and Ids: getName, setName and threadId
Names and ids identify threads in log messages and debugging tools. The name can be changed; the id is a unique number assigned by the JVM and never changes.
public class IdentityDemo {
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
Thread me = Thread.currentThread();
System.out.println("Inside: name=" + me.getName() + ", id=" + me.threadId());
});
System.out.println("Default name : " + worker.getName());
worker.setName("report-worker"); // rename before starting
System.out.println("New name : " + worker.getName());
System.out.println("toString() : " + worker);
System.out.println("isVirtual() : " + worker.isVirtual());
worker.start();
worker.join();
System.out.println("Main thread id: " + Thread.currentThread().threadId());
}
}
Output (the id of report-worker can be a different number on your machine):
Default name : Thread-0
New name : report-worker
toString() : Thread[#19,report-worker,5,main]
isVirtual() : false
Inside: name=report-worker, id=19
Main thread id: 1
How it works:
setNamechanges the name. You can call it at any time, but naming a thread before it starts keeps every log line consistent.threadId()(Java 19+) returns the unique id. The oldergetId()method still works but is deprecated.toString()showsThread[#id,name,priority,group]. Here the priority is 5 and the thread group ismain.Thread.currentThread()is a static method: it returns the thread that is running the line of code, which is how a task finds out where it is running.- The JVM creates several internal threads at startup, which is why the first thread you create gets an id like 19 rather than 2.
Checking if a Thread Is Running: isAlive and getState
isAlive() returns true from the moment a thread is started until its run() method ends. getState() gives more detail as a Thread.State value.
public class AliveStateDemo {
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
try {
Thread.sleep(300); // pretend to work for 300 ms
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}, "worker");
print("before start()", worker);
worker.start();
Thread.sleep(100);
print("while working ", worker);
worker.join();
print("after join() ", worker);
}
static void print(String moment, Thread t) {
System.out.println(moment + ": isAlive=" + t.isAlive() + ", state=" + t.getState());
}
}
Output:
before start(): isAlive=false, state=NEW
while working : isAlive=true, state=TIMED_WAITING
after join() : isAlive=false, state=TERMINATED
How it works:
- Before
start(), the thread exists only as an object: it isNEWand not alive. - While it sleeps, it is alive and in the
TIMED_WAITINGstate. - After
run()ends, it isTERMINATEDand no longer alive. A terminated thread cannot be started again.
The Java Thread States lesson explains all six states and how a thread moves between them.
Thread Priority: getPriority and setPriority
Every thread has a priority from 1 (lowest) to 10 (highest). A new thread gets the same priority as the thread that created it, which is normally 5. The Thread class defines three constants for the common values.
public class PriorityDemo {
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 backup = new Thread(() -> {}, "backup");
backup.setPriority(Thread.MIN_PRIORITY);
Thread ui = new Thread(() -> {}, "ui-refresh");
ui.setPriority(Thread.MAX_PRIORITY);
System.out.println(backup.getName() + " priority = " + backup.getPriority());
System.out.println(ui.getName() + " priority = " + ui.getPriority());
try {
ui.setPriority(11); // outside 1..10
} catch (IllegalArgumentException e) {
System.out.println("setPriority(11): IllegalArgumentException");
}
}
}
Output:
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
backup priority = 1
ui-refresh priority = 10
setPriority(11): IllegalArgumentException
How it works:
setPriorityaccepts only values from 1 to 10; anything else throwsIllegalArgumentException.- The priority is a hint to the operating system's scheduler. Many systems, including most Linux setups, ignore Java priorities completely.
Note: Never use priorities to make a program correct, for example to make one thread finish before another. Use
join()or other coordination tools instead. The Thread Priority lesson later in this section goes into the details.
Daemon Threads: isDaemon and setDaemon
A daemon thread is a background thread that does not keep the JVM alive. When all non-daemon (user) threads have finished, the JVM exits and stops any daemon threads that are still running. A new thread inherits the daemon status of the thread that created it.
public class DaemonFlagDemo {
public static void main(String[] args) throws InterruptedException {
Thread cleaner = new Thread(() -> {
try {
Thread.sleep(200); // stays alive for a moment
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}, "cache-cleaner");
System.out.println("Default isDaemon: " + cleaner.isDaemon()); // inherited from main (false)
cleaner.setDaemon(true); // allowed: not started yet
System.out.println("After setDaemon : " + cleaner.isDaemon());
cleaner.start();
try {
cleaner.setDaemon(false); // not allowed while the thread is alive
} catch (IllegalThreadStateException e) {
System.out.println("setDaemon while running: IllegalThreadStateException");
}
cleaner.join();
}
}
Output:
Default isDaemon: false
After setDaemon : true
setDaemon while running: IllegalThreadStateException
How it works:
- The new thread was created by
main, which is a user thread, so it starts as a user thread (false). setDaemon(true)works because the thread has not started yet.- Once the thread is alive, its daemon status is fixed, and
setDaemonthrowsIllegalThreadStateException. - Virtual threads are always daemon threads, and their daemon status cannot be changed.
Stopping a Thread Safely with interrupt()
Java has no safe way to force a thread to stop. Instead, you ask it to stop with interrupt(), and the thread's code decides how to react. Interrupting does two things:
- It sets the thread's interrupt flag, which the thread can check with
isInterrupted(). - If the thread is sleeping or waiting (
sleep,join,wait), that call ends immediately with anInterruptedException, and the flag is cleared.
| Method | Type | What it does |
|---|---|---|
t.interrupt() | Instance | Requests that thread t stop |
t.isInterrupted() | Instance | Reads t's interrupt flag; does not change it |
Thread.interrupted() | Static | Reads the current thread's flag and clears it |
public class InterruptDemo {
public static void main(String[] args) throws InterruptedException {
// 1. A busy loop that checks the interrupt flag
Thread counter = new Thread(() -> {
long count = 0;
while (!Thread.currentThread().isInterrupted()) {
count++;
}
System.out.println("counter stopped politely (count > 0: " + (count > 0) + ")");
}, "counter");
// 2. A sleeping thread: interrupt() wakes it with an InterruptedException
Thread sleeper = new Thread(() -> {
try {
Thread.sleep(10_000);
System.out.println("sleeper woke up normally");
} catch (InterruptedException e) {
System.out.println("sleeper interrupted during sleep");
System.out.println("flag after exception: " + Thread.currentThread().isInterrupted());
}
}, "sleeper");
counter.start();
sleeper.start();
Thread.sleep(200);
counter.interrupt(); // request: please stop
sleeper.interrupt();
counter.join();
sleeper.join();
// Thread.interrupted() reads AND clears the flag of the current thread
Thread.currentThread().interrupt();
System.out.println("interrupted() first call : " + Thread.interrupted());
System.out.println("interrupted() second call: " + Thread.interrupted());
}
}
Output (the first two lines can appear in either order):
counter stopped politely (count > 0: true)
sleeper interrupted during sleep
flag after exception: false
interrupted() first call : true
interrupted() second call: false
How it works:
- The
counterloop checksisInterrupted()on every pass. When main interrupts it, the loop ends and the thread finishes cleanly. - The
sleeperwould have slept for 10 seconds, butinterrupt()wakes it at once with anInterruptedException. The output shows that the flag isfalseafterwards, because throwing the exception clears it. Thread.interrupted()returnedtruethe first time andfalsethe second time, because it clears the flag as it reads it.
Note: When you catch
InterruptedExceptionbut cannot stop right there, restore the flag withThread.currentThread().interrupt(). That is why the examples in this section use that line inside theircatchblocks: it lets code further up notice the stop request.
Handling Errors in Threads: UncaughtExceptionHandler
An exception thrown inside a thread's run() method does not reach the code that started the thread. If nobody catches it, the thread ends and, by default, the stack trace is printed to the error output. An uncaught exception handler lets you decide what happens instead, for example logging the error.
public class UncaughtDemo {
public static void main(String[] args) throws InterruptedException {
Thread parser = new Thread(() -> {
String quantity = "twelve";
int value = Integer.parseInt(quantity); // throws NumberFormatException
System.out.println("Parsed " + value);
}, "csv-parser");
// Called when run() ends with an exception nobody caught
parser.setUncaughtExceptionHandler((thread, error) ->
System.out.println("[" + thread.getName() + "] failed: " + error));
parser.start();
parser.join();
System.out.println("main continues normally");
}
}
Output:
[csv-parser] failed: java.lang.NumberFormatException: For input string: "twelve"
main continues normally
How it works:
Integer.parseInt("twelve")throws inside thecsv-parserthread, and nothing inrun()catches it.- The handler receives the thread and the exception, and prints a short log line instead of a full stack trace.
- The main thread is not affected: a failure in one thread does not stop the others.
Thread.setDefaultUncaughtExceptionHandler(handler)sets a handler for all threads that have none of their own.
Java Thread Class Methods: Quick Reference
| Method | Purpose |
|---|---|
start() | Start the thread; it then calls run() |
run() | The code the thread executes; do not call it directly |
Thread.currentThread() | The thread running the current code |
getName() / setName(String) | Read or change the name |
threadId() | Unique id (Java 19+; replaces getId()) |
isAlive() | true between start() and the end of run() |
getState() | Current Thread.State value |
getPriority() / setPriority(int) | Scheduling hint from 1 to 10 |
isDaemon() / setDaemon(boolean) | Background thread flag; set before start() |
isVirtual() | Whether this is a virtual thread (Java 21+) |
Thread.sleep(millis) | Pause the current thread |
join() / join(millis) | Wait for the thread to end, optionally with a time limit |
interrupt() / isInterrupted() / Thread.interrupted() | Request and detect a stop |
setUncaughtExceptionHandler(handler) | Handle exceptions that escape run() |
Note:
stop(),suspend()andresume()still appear in old tutorials. They are unsafe because they can leave shared data half-updated, and in current Java versions they throwUnsupportedOperationException. Useinterrupt()instead.
Real-World Example: Background Job Runner
A data import service runs several import jobs at once. It needs readable log lines that show which job did what, a heartbeat that never blocks shutdown, a time limit for slow jobs, and error handling for jobs that fail. This example combines most of the Thread methods from this lesson.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
public class JobRunner {
static final long START = System.currentTimeMillis();
static void log(String message) {
long ms = System.currentTimeMillis() - START;
System.out.printf("%5d ms [%-16s] %s%n", Math.round(ms / 100.0) * 100,
Thread.currentThread().getName(), message);
}
// A job that processes items until it is done or interrupted
static Runnable importJob(String source, int items, int failAt) {
return () -> {
for (int item = 1; item <= items; item++) {
if (Thread.currentThread().isInterrupted()) {
log("stopped early after " + (item - 1) + " items");
return;
}
if (item == failAt) {
throw new IllegalStateException("bad record #" + item + " in " + source);
}
try {
Thread.sleep(100); // processing one item
} catch (InterruptedException e) {
log("interrupted while processing item " + item);
return;
}
}
log("imported " + items + " items from " + source);
};
}
public static void main(String[] args) throws InterruptedException {
AtomicInteger failures = new AtomicInteger();
// Daemon heartbeat: dies automatically when the workers are done
Thread heartbeat = new Thread(() -> {
while (true) {
try {
Thread.sleep(250);
} catch (InterruptedException e) {
return;
}
log("still alive");
}
}, "heartbeat");
heartbeat.setDaemon(true);
heartbeat.setPriority(Thread.MIN_PRIORITY);
heartbeat.start();
List<Thread> workers = new ArrayList<>();
workers.add(new Thread(importJob("customers.csv", 3, -1), "import-customers"));
workers.add(new Thread(importJob("orders.csv", 10, -1), "import-orders"));
workers.add(new Thread(importJob("products.csv", 5, 2), "import-products"));
for (Thread worker : workers) {
worker.setUncaughtExceptionHandler((t, e) -> {
failures.incrementAndGet();
log("FAILED: " + e.getMessage());
});
worker.start();
}
Thread orders = workers.get(1);
orders.join(600); // wait at most 600 ms for the slow job
if (orders.isAlive()) {
log("orders job is too slow, interrupting " + orders.getName());
orders.interrupt();
}
for (Thread worker : workers) {
worker.join();
}
log("all jobs ended, failures = " + failures.get()
+ ", heartbeat daemon = " + heartbeat.isDaemon());
}
}
Output from one run (times are rounded to 100 ms; the interrupted item number can be 6 or 7):
100 ms [import-products ] FAILED: bad record #2 in products.csv
300 ms [heartbeat ] still alive
300 ms [import-customers] imported 3 items from customers.csv
500 ms [heartbeat ] still alive
600 ms [main ] orders job is too slow, interrupting import-orders
600 ms [import-orders ] interrupted while processing item 7
600 ms [main ] all jobs ended, failures = 1, heartbeat daemon = true
How it works:
- Named threads make logs readable.
logprintsThread.currentThread().getName(), so every line shows which job produced it, without passing the job name around. - Daemon heartbeat. The heartbeat loop never ends by itself. Because it is a daemon with the lowest priority, it never prevents the program from exiting.
- Failure handling. The products job throws on record 2. Its uncaught exception handler logs the message and counts the failure in an
AtomicInteger, a counter that is safe to update from several threads. - Time limit with
join(millis). Main waits at most 600 ms for the orders job.isAlive()then shows it is still running, so main callsinterrupt(). - Cooperative stop. The orders job is sleeping when the interrupt arrives, so
sleepthrowsInterruptedException. The job logs how far it got and returns, which ends the thread cleanly. - Final join. Main joins every worker before printing the summary. When main ends, only the daemon heartbeat is left, so the JVM exits.
The tasks in this example are Runnable objects created by a method. The next lesson, Java Runnable Interface, looks at Runnable in depth. For the basics of how threads share memory and why the result counter is atomic, see Java Threads: Thread Basics.