Creating Threads in Java: Thread, Runnable and Lambdas
Three ways to give a thread its job: an InvoiceMailer that extends Thread, a ReportTask record that implements Runnable, and a lambda. worker.run() prints main, worker.start() prints backup-worker, and two cashiers, Jack and Liam, scan items in an order that changes every run.
What you will learn
- Create a thread by extending Thread and overriding run
- Hand a Runnable job, as a record or a lambda, to a named Thread
- Explain why start() makes a new thread and run() does not
- Expect the output of two threads to interleave differently on each run
Before you start
- Why concurrency: processes, threads and the main thread
- Java lambdas and functional interfaces
There are three ways to give a Java thread its job, and one call that matters more than any of them: start(). Threads run side by side, so wherever two of them print, the order of lines can change from run to run.
A class that is a worker
package org.studyeasy.s06l02;
public class Ex01_ExtendThread {
// Extending Thread: this class IS a worker, and run() is its job
static class InvoiceMailer extends Thread {
@Override
public void run() {
String me = Thread.currentThread().getName();
for (int invoice = 101; invoice <= 103; invoice++) {
System.out.println(me + " mails invoice #" + invoice);
}
}
}
public static void main(String[] args) {
InvoiceMailer mailer = new InvoiceMailer();
mailer.start(); // start() creates the thread
}
}
Thread-0 mails invoice #101
Thread-0 mails invoice #102
Thread-0 mails invoice #103
InvoiceMailer extends Thread and overrides run. The class is the worker and run is its job. Creating the object doesn't start anything; start() creates the thread, which Java names Thread-0 because we gave it no name.
Only the job, handed to a Thread
// Implementing Runnable: only the job, no thread yet
record ReportTask(String report) implements Runnable {
@Override
public void run() {
String me = Thread.currentThread().getName();
System.out.println(me + " builds the " + report);
}
}
ReportTask task = new ReportTask("March sales report");
Thread worker = new Thread(task, "report-worker"); // job + name
System.out.println("Starting " + worker.getName());
worker.start(); // the worker thread runs task.run()
Starting report-worker
report-worker builds the March sales report
This is the more common way. Runnable is just the job; here it's a record, which works fine as long as it implements Runnable. You make the job first, then hand it to a Thread along with a name. With extends Thread, the job lives inside the worker; with Runnable, job and worker are separate, so your class is still free to extend something else.
A lambda as the job
// Runnable has one method, run(), so a lambda can be the job
Runnable backup = () -> {
String me = Thread.currentThread().getName();
System.out.println(me + " backs up the orders table");
};
Thread worker = new Thread(backup, "backup-worker");
worker.start();
backup-worker backs up the orders table
Runnable has one method, so a lambda can be the whole job. No class at all.
start() opens a new lane, run() does not
Thread worker = new Thread(backup, "backup-worker");
worker.run(); // a plain method call: main does the work
worker.start(); // a new thread: backup-worker does the work
main backs up the orders table
backup-worker backs up the orders table
run() is an ordinary method call: no new thread, so main does the job and the output says main. start() asks Java for a new thread, which then calls run() for you. A Thread can be started only once; a second start() throws IllegalThreadStateException.
Two cashiers, one job
static void scan() { // scanning one item takes time
try { Thread.sleep(100); } catch (InterruptedException e) { }
}
// One job, two cashiers: each thread runs its own loop
Runnable checkout = () -> {
String cashier = Thread.currentThread().getName();
for (int item = 1; item <= 3; item++) {
scan();
System.out.println(cashier + " scans item " + item);
}
};
new Thread(checkout, "Jack").start();
new Thread(checkout, "Liam").start();
// main does not wait for them: it carries on at once
System.out.println("main opened both lanes");
main opened both lanes
Jack scans item 1
Liam scans item 1
Jack scans item 2
Liam scans item 2
Liam scans item 3
Jack scans item 3
This is one real run; yours may differ. Main starts both threads and prints its line straight away, without waiting. Jack and Liam each run their own loop and scan in parallel, sharing one console, so their lines interleave. In this run Liam printed item 3 just before Jack. Look at each pair rather than the exact order.
Recap
| Way | Code |
|---|---|
| Extend Thread | class InvoiceMailer extends Thread { public void run() {...} } |
| Implement Runnable | new Thread(new ReportTask(...), "report-worker") |
| Lambda | new Thread(() -> {...}, "backup-worker") |
| Start it | start(), never run(), and only once |
Next: making a thread wait with sleep, join and interrupt.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Why Concurrency: Processes, Threads and the Main Thread in Java
Every Java program runs as a process and starts on one thread, main. One cook takes 15 seconds for soup and salad; a second thread, Jack, brings it to 10. Then two threads add to one counter a million times each and count less than 2,000,000.
Java Thread Lifecycle: sleep, join and interrupt
A courier thread walks from NEW through RUNNABLE and TIMED_WAITING to TERMINATED while main WAITs at join. An interrupt wakes a sleeping download on report-3: one version retries it, the other returns. And a daemon status thread dies when the last user thread ends.
Java Race Conditions and synchronized
Two cashiers each sell a million tickets on one counter and the total comes out short, a different number every run, because sold++ is read, add, write. A synchronized method or a synchronized block on one shared lock gives exactly 2,000,000; a new Object() lock protects nothing.
Java volatile and Atomic Variables
main sets a volatile running flag to false and the sync job finishes batch 3, sees the change and exits. But volatile can't make views++ one step, so two threads still lose updates. An AtomicInteger with incrementAndGet counts web and mobile visits to exactly 200,000.
