Java Thread Class

Su Suriya Ravichandran Updated 18 Nov 2026
13 min read ·Lesson 183 of 306

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.

ConstructorCreates
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-0 and idle-thread have no task. Their run() method is empty, so they start and end without printing anything.
  • Thread-1 and invoice-printer run the shared task, 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() and Thread.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:

  • setName changes 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 older getId() method still works but is deprecated.
  • toString() shows Thread[#id,name,priority,group]. Here the priority is 5 and the thread group is main.
  • 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 is NEW and not alive.
  • While it sleeps, it is alive and in the TIMED_WAITING state.
  • After run() ends, it is TERMINATED and 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:

  • setPriority accepts only values from 1 to 10; anything else throws IllegalArgumentException.
  • 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 setDaemon throws IllegalThreadStateException.
  • 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 an InterruptedException, and the flag is cleared.
MethodTypeWhat it does
t.interrupt()InstanceRequests that thread t stop
t.isInterrupted()InstanceReads t's interrupt flag; does not change it
Thread.interrupted()StaticReads 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 counter loop checks isInterrupted() on every pass. When main interrupts it, the loop ends and the thread finishes cleanly.
  • The sleeper would have slept for 10 seconds, but interrupt() wakes it at once with an InterruptedException. The output shows that the flag is false afterwards, because throwing the exception clears it.
  • Thread.interrupted() returned true the first time and false the second time, because it clears the flag as it reads it.

Note: When you catch InterruptedException but cannot stop right there, restore the flag with Thread.currentThread().interrupt(). That is why the examples in this section use that line inside their catch blocks: 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 the csv-parser thread, and nothing in run() 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

MethodPurpose
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() and resume() still appear in old tutorials. They are unsafe because they can leave shared data half-updated, and in current Java versions they throw UnsupportedOperationException. Use interrupt() 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:

  1. Named threads make logs readable. log prints Thread.currentThread().getName(), so every line shows which job produced it, without passing the job name around.
  2. 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.
  3. 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.
  4. Time limit with join(millis). Main waits at most 600 ms for the orders job. isAlive() then shows it is still running, so main calls interrupt().
  5. Cooperative stop. The orders job is sleeping when the interrupt arrives, so sleep throws InterruptedException. The job logs how far it got and returns, which ends the thread cleanly.
  6. 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.

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 Class and get answers drawn from it.

Signed-in readers only.