Create a Thread in Java
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
| Way | How | When to use it |
|---|---|---|
Extend Thread | class MyThread extends Thread { public void run() {...} } | Small programs where the class is only a thread |
Implement Runnable | class MyTask implements Runnable { public void run() {...} } then new Thread(task) | Reusable tasks; the class can still extend another class |
| Lambda | new Thread(() -> {...}) | Short tasks; the most common modern style |
| Anonymous class | new 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:
DownloadThreadis aThread, so it inheritsstart(),getName(),join()and every otherThreadmethod.super("download-" + fileName)calls theThread(String name)constructor to give the thread a readable name.- Inside
run(), the code can callgetName()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
Threadcannot extend anything else, which is the main reason most code prefersRunnable.
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:
EmailTaskis just a task. It is not a thread, so it has nogetName(). To find out which thread runs it, it callsThread.currentThread().new Thread(task, "mailer-1")wraps the task in a thread with a name. When the thread starts, it callstask.run().- Because
EmailTaskonly 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 aRunnablewhoserun()method contains one statement. For several statements, use braces{ ... }.- The anonymous class
new Thread("logger") { ... }creates an unnamed subclass ofThreadon the spot and overridesrun(). 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
Runnableis 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 theNEWstate without running it, likenew 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 method | Purpose |
|---|---|
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 onmain. 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 calledrun(). The output shows the nameworker.- After a thread has been started once, calling
start()again throwsIllegalThreadStateException, even when the thread has already finished. To run the task again, create a newThread.
start() | run() | |
|---|---|---|
| Creates a new thread | Yes | No |
| Where the code runs | On the new thread | On the calling thread |
| Caller waits for it | No, returns immediately | Yes, like any method |
| Can be called twice | No (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
PriceCalculatorgets its product data through the constructor and stores the result in its owntotalfield. - Main keeps a reference to each task object, so after
join()it can callgetTotal()to read the result. join()is essential: it waits for the thread to finish and guarantees main sees the value oftotalthat the thread wrote. Readingtotalwithoutjoin()could give0.0.- The lambda uses
customerandorderIdsafely 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
CallableandFuture, 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:
- One thread object per document. A stream turns each map entry into a
WordCounterand collects them into an array. The thread name is built from the title, such ascounter-java-intro. - 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.
- 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. - Private results. Each thread writes only its own
wordsandlongestWordfields, so no two threads ever change the same data. - Combining on main. After every
join(), main reads all the fields safely, prints a line per document, and usesreduceto 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.