Create a thread with Thread and Runnable
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A thread needs a task: the code it will run. Java lets you write that task by extending Thread, by implementing Runnable, or with a lambda, and you then call start() to set the new thread going.
Extending Thread and overriding run()
Extending Thread means writing a subclass of java.lang.Thread and putting the new thread's work inside its run() method. You create an object of the subclass and call start(); the new thread then calls run() for you.
Example 1 · A thread by extending Thread
class TicketPrinter extends Thread { private final int tickets;
TicketPrinter(String name, int tickets) { super(name); // the Thread(String name) constructor sets the name this.tickets = tickets; }
@Override public void run() { for (int i = 1; i <= tickets; i++) { System.out.println(getName() + " printed ticket " + i); } }}
public class ExtendThreadDemo { public static void main(String[] args) throws InterruptedException { TicketPrinter printer = new TicketPrinter("printer-1", 3); System.out.println("main: starting " + printer.getName());
printer.start(); // a new thread begins and calls run() printer.join(); // main waits here until printer-1 finishes
System.out.println("main: " + printer.getName() + " is done"); }}main: starting printer-1 printer-1 printed ticket 1 printer-1 printed ticket 2 printer-1 printed ticket 3 main: printer-1 is done
What this code does
TicketPrinteris aThread, so insiderun()it can call its owngetName().super(name)passes the name toThread's constructor.start()begins a new thread that runsrun(). Becausemaincallsjoin()straight away, the tickets always print before the last line.
The run() method must be exactly public void run(): no parameters, no return value. Data the task needs goes in through the constructor and fields. The examples call join() on the thread. It makes main wait until that thread has finished, so the output comes in a fixed order. The lesson Pause and wait: sleep and join covers it fully.
Implementing Runnable and passing it to Thread
Runnable is an interface with one method, void run(), that describes a task. You write a class that implements it and hand an object of it to the Thread constructor: new Thread(task, "block-A"). The thread runs that task.
Example 2 · A Runnable task for each hostel block
class FeeTotal implements Runnable { private final int[] fees; private long total; // filled in by run()
FeeTotal(int[] fees) { this.fees = fees; }
@Override public void run() { for (int fee : fees) { total += fee; } }
long getTotal() { return total; }}
public class RunnableDemo { public static void main(String[] args) throws InterruptedException { FeeTotal blockA = new FeeTotal(new int[] {42000, 42000, 38500, 45000}); FeeTotal blockB = new FeeTotal(new int[] {39000, 41000, 41000});
Thread a = new Thread(blockA, "block-A"); Thread b = new Thread(blockB, "block-B"); a.start(); b.start(); a.join(); b.join();
System.out.println("Block A fees: Rs " + blockA.getTotal()); System.out.println("Block B fees: Rs " + blockB.getTotal()); System.out.println("Hostel total: Rs " + (blockA.getTotal() + blockB.getTotal())); }}Block A fees: Rs 167500 Block B fees: Rs 121000 Hostel total: Rs 288500
What this code does
FeeTotalis only a task: it does not know about threads. EachThreadgets its ownFeeTotalobject, and both threads add up their block at the same time.mainreadsgetTotal()only after bothjoin()calls, when both threads have finished. Each thread writes only its own object, so they never touch the same data.
This splits two things apart: the task (what to do, your Runnable) and the worker (the Thread that does it). The task class stays an ordinary class, so it can extend another class, keep fields and be tested by calling run() yourself.
Order of execution
Order of creating a thread
Put the steps in the order they happen when you run a task on a new thread.
new Thread(task, name) takes the task first and the thread's name second.Runnable as a lambda
Because Runnable has exactly one abstract method, it is a functional interface, so a lambda can stand in for it: new Thread(() -> sendReminders(), "reminder"). A method reference such as RemindersDemo::sendReminders works too, when the method takes no arguments and returns void.
Example 3 · Lambdas and a method reference as tasks
public class LambdaThreadDemo { static String[] results = new String[3];
static void sendReminders() { results[2] = Thread.currentThread().getName() + " sent 120 fee reminders"; }
public static void main(String[] args) throws InterruptedException { int seats = 60; // effectively final: never changed
Thread booking = new Thread(() -> { results[0] = Thread.currentThread().getName() + " booked " + seats + " seats"; }, "booking");
Thread report = new Thread(() -> results[1] = "report counted " + (seats * 3) + " tickets", "report");
Thread reminder = new Thread(LambdaThreadDemo::sendReminders, "reminder");
booking.start(); report.start(); reminder.start(); booking.join(); report.join(); reminder.join();
for (String r : results) { System.out.println(r); } }}booking booked 60 seats report counted 180 tickets reminder sent 120 fee reminders
What this code does
- Each lambda becomes the
run()method of aRunnable.LambdaThreadDemo::sendRemindersworks because the method takes nothing and returnsvoid, just likerun(). - Every thread writes a different slot of
results, andmainprints them after joining all three, so the output order is fixed.seatscan be used inside the lambdas because it never changes.
This is the shortest way to start a small task and the one you see most in modern code. A lambda can use local variables from the method around it only if they are effectively final: never changed after they get their value.
Naming threads and Thread.currentThread().getName()
Thread.currentThread() returns the thread running the current line, and getName() returns its name. Inside a Runnable or a lambda this is the only way to find out which thread is running the task.
Example 4 · Default names versus your own names
public class ThreadNamesDemo { public static void main(String[] args) throws InterruptedException { Runnable whoAmI = () -> System.out.println("running on " + Thread.currentThread().getName());
Thread first = new Thread(whoAmI); // no name given Thread second = new Thread(whoAmI); // no name given Thread named = new Thread(whoAmI, "seat-allocator"); Thread renamed = new Thread(whoAmI); System.out.println("Names: " + first.getName() + ", " + second.getName() + ", " + named.getName() + ", " + renamed.getName());
renamed.setName("payment-checker"); // rename before start()
for (Thread t : new Thread[] {first, second, named, renamed}) { t.start(); t.join(); } System.out.println("running on " + Thread.currentThread().getName()); }}Names: Thread-0, Thread-1, seat-allocator, Thread-2 running on Thread-0 running on Thread-1 running on seat-allocator running on payment-checker running on main
What this code does
- Unnamed threads get
Thread-0,Thread-1and so on. Only unnamed threads use up a number, sorenamedisThread-2untilsetNamechanges it (a program that created other threads first gets higher numbers). - The same
Runnableprints a different name on each thread:Thread.currentThread()asks "who is running me now?". The last line runs onmain. Joining each thread before starting the next is only for a fixed output order.
A thread created without a name gets a default one: Thread-0, Thread-1 and so on, numbered in the order the threads were created. Give real names instead, with new Thread(task, "seat-allocator") or setName(...) before start(). Logs and error messages then tell you which worker did what.
Thread or Runnable: which to choose
Prefer Runnable (or a lambda) in almost every case. Java allows only one superclass, so a class that extends Thread cannot extend anything else. A Runnable class keeps that slot free.
Example 5 · A task class that also extends another class
class Reminder { protected final String student;
Reminder(String student) { this.student = student; }
String text() { return "Dear " + student + ", please pay your fees"; }}
// Extends Reminder AND is a task: possible only with Runnable.class FeeReminder extends Reminder implements Runnable { private final int dueAmount; private String sent;
FeeReminder(String student, int dueAmount) { super(student); this.dueAmount = dueAmount; }
@Override public void run() { sent = text() + " (Rs " + dueAmount + ")"; }
String getSent() { return sent; }}
public class ChooseRunnableDemo { public static void main(String[] args) throws InterruptedException { FeeReminder r1 = new FeeReminder("Priya", 12500); FeeReminder r2 = new FeeReminder("Kabir", 8000);
Thread t1 = new Thread(r1, "sms-1"); Thread t2 = new Thread(r2, "sms-2"); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println(r1.getSent()); System.out.println(r2.getSent());
r1.run(); // a Runnable is a normal object: easy to call in a test System.out.println("Direct call worked: " + (r1.getSent() != null)); }}Dear Priya, please pay your fees (Rs 12500) Dear Kabir, please pay your fees (Rs 8000) Direct call worked: true
What this code does
FeeReminderalready extendsReminder, so it could not also extendThread. ImplementingRunnablekeeps the class hierarchy free.- Calling
r1.run()directly runs the task onmain, with no thread. That makes Runnable tasks easy to test; the next lesson shows why you must usestart()when you want a new thread.
- Extending
Thread: short to write, but uses up the one superclass. - Implementing
Runnable: task and worker stay separate; the class can extend another class. - Lambda: shortest for small tasks; uses effectively final local variables.
A Runnable is also just a task, so the same object can be given to a thread now and, in later modules, to a thread pool (an ExecutorService) without changes. Extending Thread mixes the task with the worker and is rarely needed outside small demos.
Next step
Check your understanding
12 quick questions