Create a Thread in Java

Su Suriya Ravichandran Updated 18 Nov 2026
12 min read ·Lesson 182 of 306

To create a thread in Java, you describe the work the thread should do and then call start() to run that work on a new thread. Java gives you several ways to describe the work: extending the Thread class, implementing Runnable, writing a lambda, using an anonymous class, or using the Thread.Builder API added in Java 21.

This lesson shows each way with a runnable example, explains the important difference between start() and run(), and shows how to pass data into a thread and get results back.


Ways to Create a Thread in Java

WayHowWhen to use it
Extend Threadclass MyThread extends Thread { public void run() {...} }Small programs where the class is only a thread
Implement Runnableclass MyTask implements Runnable { public void run() {...} } then new Thread(task)Reusable tasks; the class can still extend another class
Lambdanew Thread(() -> {...})Short tasks; the most common modern style
Anonymous classnew Thread() { public void run() {...} }Older code written before Java 8
Thread builder (Java 21+)Thread.ofPlatform().start(task), Thread.ofVirtual().start(task)Naming threads consistently, creating virtual threads

All of them end the same way: a Thread object whose start() method launches a new thread, which then calls the task's run() method.


Way 1: Create a Thread by Extending the Thread Class

The Thread class has a run() method that does nothing by default. You can create a subclass, override run() with your own code, and start an instance of that subclass.

Syntax:

class MyThread extends Thread {
    @Override
    public void run() {
        // code that runs on the new thread
    }
}

MyThread thread = new MyThread();
thread.start();

Example:

public class ExtendThreadDemo {
    public static void main(String[] args) throws InterruptedException {
        DownloadThread first = new DownloadThread("notes.pdf");
        DownloadThread second = new DownloadThread("video.mp4");

        first.start();
        second.start();
        first.join();
        second.join();
        System.out.println("main is done");
    }
}

// Way 1: extend the Thread class and override run()
class DownloadThread extends Thread {
    private final String fileName;

    DownloadThread(String fileName) {
        super("download-" + fileName); // set the thread name
        this.fileName = fileName;
    }

    @Override
    public void run() {
        System.out.println(getName() + " is downloading " + fileName);
    }
}

Output (the first two lines can appear in either order):

download-notes.pdf is downloading notes.pdf
download-video.mp4 is downloading video.mp4
main is done

How it works:

  • DownloadThread is a Thread, so it inherits start(), getName(), join() and every other Thread method.
  • super("download-" + fileName) calls the Thread(String name) constructor to give the thread a readable name.
  • Inside run(), the code can call getName() directly because the object itself is the thread.
  • join() makes main wait until both downloads finish before printing its own message.

Note: Java allows only one superclass. A class that extends Thread cannot extend anything else, which is the main reason most code prefers Runnable.


Way 2: Create a Thread by Implementing Runnable

Runnable is an interface with a single method, void run(). You put the work in a class that implements Runnable, then hand an instance of it to a Thread. The task (the Runnable) and the worker (the Thread) are now separate objects.

Syntax:

class MyTask implements Runnable {
    @Override
    public void run() {
        // code that runs on the new thread
    }
}

Thread thread = new Thread(new MyTask(), "optional-name");
thread.start();

Example:

public class RunnableDemo {
    public static void main(String[] args) throws InterruptedException {
        Thread mailer1 = new Thread(new EmailTask("asha@example.com"), "mailer-1");
        Thread mailer2 = new Thread(new EmailTask("ravi@example.com"), "mailer-2");

        mailer1.start();
        mailer2.start();
        mailer1.join();
        mailer2.join();
        System.out.println("All emails sent");
    }
}

// Way 2: implement Runnable and pass it to a Thread
class EmailTask implements Runnable {
    private final String recipient;

    EmailTask(String recipient) {
        this.recipient = recipient;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + " sends email to " + recipient);
    }
}

Output (the first two lines can appear in either order):

mailer-1 sends email to asha@example.com
mailer-2 sends email to ravi@example.com
All emails sent

How it works:

  • EmailTask is just a task. It is not a thread, so it has no getName(). To find out which thread runs it, it calls Thread.currentThread().
  • new Thread(task, "mailer-1") wraps the task in a thread with a name. When the thread starts, it calls task.run().
  • Because EmailTask only implements an interface, it could still extend another class if needed.

The Java Runnable Interface lesson covers Runnable in much more depth.


Way 3 and 4: Create a Thread with a Lambda or an Anonymous Class

Since Runnable has exactly one abstract method, it is a functional interface. That means you can write the task as a lambda expression instead of a separate class. Before Java 8, the short form was an anonymous class.

public class LambdaThreadDemo {
    public static void main(String[] args) throws InterruptedException {
        // Way 3: a lambda expression is the shortest way to write a Runnable
        Thread printer = new Thread(() -> System.out.println("Printing invoice on " + Thread.currentThread().getName()), "printer");

        // A lambda with several statements
        Thread counter = new Thread(() -> {
            int total = 0;
            for (int n = 1; n <= 10; n++) {
                total += n;
            }
            System.out.println("Sum 1..10 = " + total + " on " + Thread.currentThread().getName());
        }, "counter");

        // Way 4: an anonymous class (older style, more verbose)
        Thread logger = new Thread("logger") {
            @Override
            public void run() {
                System.out.println("Writing log entry on " + getName());
            }
        };

        printer.start();
        printer.join();
        counter.start();
        counter.join();
        logger.start();
        logger.join();
    }
}

Output:

Printing invoice on printer
Sum 1..10 = 55 on counter
Writing log entry on logger

How it works:

  • () -> System.out.println(...) is a Runnable whose run() method contains one statement. For several statements, use braces { ... }.
  • The anonymous class new Thread("logger") { ... } creates an unnamed subclass of Thread on the spot and overrides run(). It is Way 1 written inline.
  • Each thread is started and joined before the next one starts, so the output order is fixed here.

Note: Lambdas are the usual choice for short tasks. When the task needs several fields, helper methods, or reuse in many places, a named class that implements Runnable is clearer.


Way 5: Create Threads with Thread.Builder (Java 21+)

Java 21 added the Thread.Builder API. Thread.ofPlatform() returns a builder for normal (platform) threads and Thread.ofVirtual() returns a builder for virtual threads. A builder can set the name, daemon status and other options, then either start(task) the thread or create it unstarted(task).

public class BuilderDemo {
    public static void main(String[] args) throws InterruptedException {
        Runnable task = () -> System.out.println("Running on " + Thread.currentThread().getName()
                + " (virtual = " + Thread.currentThread().isVirtual() + ")");

        // Platform threads with automatic names worker-1, worker-2, ...
        Thread.Builder platformBuilder = Thread.ofPlatform().name("worker-", 1);
        Thread w1 = platformBuilder.start(task);
        w1.join();
        Thread w2 = platformBuilder.start(task);
        w2.join();

        // A virtual thread that is created but not started yet
        Thread lazy = Thread.ofVirtual().name("report-builder").unstarted(task);
        System.out.println("lazy state before start: " + lazy.getState());
        lazy.start();
        lazy.join();

        // Shortcut: create and start a virtual thread in one call
        Thread quick = Thread.startVirtualThread(task);
        quick.join();
    }
}

Output:

Running on worker-1 (virtual = false)
Running on worker-2 (virtual = false)
lazy state before start: NEW
Running on report-builder (virtual = true)
Running on  (virtual = true)

How it works:

  • name("worker-", 1) gives each thread from this builder a numbered name: worker-1, worker-2, and so on. The counter increases every time the builder creates a thread.
  • unstarted(task) creates the thread in the NEW state without running it, like new Thread(task).
  • Thread.startVirtualThread(task) is a one-line shortcut. Virtual threads have no name by default, which is why the last line shows an empty name.
Builder methodPurpose
name(String)Fixed name for the next thread
name(String prefix, long start)Numbered names: prefix + start, prefix + (start + 1), ...
start(Runnable)Create and start a thread
unstarted(Runnable)Create a thread without starting it
factory()Get a ThreadFactory that creates threads with these settings
daemon(boolean) (platform only)Make threads daemon or user threads

start() vs run() in Java Threads

This is the most important rule when you create a thread in Java: call start(), not run(). run() is an ordinary method. Calling it directly runs the code on the current thread, and no new thread is created.

public class StartVsRunDemo {
    public static void main(String[] args) throws InterruptedException {
        Thread worker = new Thread(
                () -> System.out.println("task runs on: " + Thread.currentThread().getName()),
                "worker");

        System.out.print("worker.run()   -> ");
        worker.run();    // just a normal method call on the main thread

        System.out.print("worker.start() -> ");
        worker.start();  // creates a new thread that calls run()
        worker.join();

        try {
            worker.start(); // a thread can only be started once
        } catch (IllegalThreadStateException e) {
            System.out.println("Second start(): " + e.getClass().getSimpleName());
        }
    }
}

Output:

worker.run()   -> task runs on: main
worker.start() -> task runs on: worker
Second start(): IllegalThreadStateException

How it works:

  • worker.run() executed the task on main. The program would wait for it to finish, exactly like any method call.
  • worker.start() asked the JVM to create a new thread, and that new thread called run(). The output shows the name worker.
  • After a thread has been started once, calling start() again throws IllegalThreadStateException, even when the thread has already finished. To run the task again, create a new Thread.
start()run()
Creates a new threadYesNo
Where the code runsOn the new threadOn the calling thread
Caller waits for itNo, returns immediatelyYes, like any method
Can be called twiceNo (IllegalThreadStateException)Yes

Passing Data to a Thread and Getting Results Back

run() takes no parameters and returns void. There are two common ways to work with that:

  • Input: pass values through the task's constructor, or let a lambda capture local variables. A lambda can only use local variables that are effectively final (never reassigned).
  • Output: let the task store its result in a field, and read that field after join().
public class PassDataDemo {
    // A Runnable that receives input through its constructor and keeps its result in a field
    static class PriceCalculator implements Runnable {
        private final String product;
        private final double price;
        private final int quantity;
        private double total; // written by the worker thread, read by main after join()

        PriceCalculator(String product, double price, int quantity) {
            this.product = product;
            this.price = price;
            this.quantity = quantity;
        }

        @Override
        public void run() {
            total = price * quantity * 1.18; // add 18% GST
        }

        double getTotal() { return total; }
        String getProduct() { return product; }
    }

    public static void main(String[] args) throws InterruptedException {
        PriceCalculator keyboard = new PriceCalculator("Keyboard", 1200.0, 2);
        PriceCalculator mouse = new PriceCalculator("Mouse", 450.0, 3);

        Thread t1 = new Thread(keyboard);
        Thread t2 = new Thread(mouse);
        t1.start();
        t2.start();
        t1.join(); // join() makes the worker's writes visible to main
        t2.join();

        System.out.printf("%s total: Rs %.2f%n", keyboard.getProduct(), keyboard.getTotal());
        System.out.printf("%s total: Rs %.2f%n", mouse.getProduct(), mouse.getTotal());

        // Lambdas can read local variables that are effectively final
        String customer = "Asha";
        int orderId = 1042;
        Thread confirm = new Thread(() -> System.out.println("Order " + orderId + " confirmed for " + customer));
        confirm.start();
        confirm.join();
    }
}

Output:

Keyboard total: Rs 2832.00
Mouse total: Rs 1593.00
Order 1042 confirmed for Asha

How it works:

  • Each PriceCalculator gets its product data through the constructor and stores the result in its own total field.
  • Main keeps a reference to each task object, so after join() it can call getTotal() to read the result.
  • join() is essential: it waits for the thread to finish and guarantees main sees the value of total that the thread wrote. Reading total without join() could give 0.0.
  • The lambda uses customer and orderId safely because they are never reassigned.

Note: Storing results in fields works for simple cases. For tasks that return a value or throw checked exceptions, Java offers Callable and Future, which later lessons in this section cover.


Real-World Example: Counting Words in Several Documents at Once

A content tool analyses several documents: it counts the words in each and finds the longest word. Each document is independent, so each one can be processed on its own thread. This example uses a Thread subclass that keeps its results in fields.

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;

public class WordCountApp {
    // Each document is counted by its own thread
    static class WordCounter extends Thread {
        private final String title;
        private final String text;
        private int words;
        private String longestWord = "";

        WordCounter(String title, String text) {
            super("counter-" + title.toLowerCase().replace(' ', '-'));
            this.title = title;
            this.text = text;
        }

        @Override
        public void run() {
            String[] tokens = text.toLowerCase().split("[^a-z]+");
            for (String token : tokens) {
                if (token.isEmpty()) continue;
                words++;
                if (token.length() > longestWord.length()) {
                    longestWord = token;
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Map<String, String> documents = new LinkedHashMap<>();
        documents.put("Java Intro", "Java is a popular, class-based, object-oriented programming language.");
        documents.put("Threads", "A thread is a lightweight unit of execution. Threads share memory.");
        documents.put("Streams", "Streams process collections declaratively; parallel streams use many threads.");

        // Create and start one thread per document
        WordCounter[] counters = documents.entrySet().stream()
                .map(e -> new WordCounter(e.getKey(), e.getValue()))
                .toArray(WordCounter[]::new);
        for (WordCounter counter : counters) {
            counter.start();
        }

        // Wait for all of them, then combine the results on main
        for (WordCounter counter : counters) {
            counter.join();
        }

        int totalWords = 0;
        for (WordCounter c : counters) {
            System.out.printf("%-11s %2d words, longest: %-16s (%s)%n",
                    c.title, c.words, c.longestWord, c.getName());
            totalWords += c.words;
        }
        String longestOverall = Arrays.stream(counters)
                .map(c -> c.longestWord)
                .reduce("", (a, b) -> b.length() > a.length() ? b : a);
        System.out.println("Total words: " + totalWords + ", longest overall: " + longestOverall);
    }
}

Output:

Java Intro  10 words, longest: programming      (counter-java-intro)
Threads     11 words, longest: lightweight      (counter-threads)
Streams      9 words, longest: declaratively    (counter-streams)
Total words: 30, longest overall: declaratively

How it works:

  1. One thread object per document. A stream turns each map entry into a WordCounter and collects them into an array. The thread name is built from the title, such as counter-java-intro.
  2. Start all, then join all. Starting every thread first and only then joining them lets all documents be processed at the same time. Starting and joining inside the same loop would process them one by one.
  3. Splitting words. split("[^a-z]+") splits on anything that is not a lowercase letter, so punctuation and hyphens separate words: "class-based" counts as two words.
  4. Private results. Each thread writes only its own words and longestWord fields, so no two threads ever change the same data.
  5. Combining on main. After every join(), main reads all the fields safely, prints a line per document, and uses reduce to find the longest word overall.

For background on what threads are and why they speed up this kind of work, see Java Threads: Thread Basics. The next lesson, Java Thread Class, explores the methods of Thread such as getName(), setDaemon() and interrupt(), and Java Thread States explains what NEW and the other states mean.

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 Create a Thread in Java and get answers drawn from it.

Signed-in readers only.