Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Multithreading

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Multithreading

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
Two lanes. worker.run() runs the backup job in main's own lane, printing main backs up the orders table. worker.start() opens a new lane named backup-worker, where the job runs while main carries on in its own lane. mainbackup-worker run(): job on main start(): job here calling start() twice on one Thread: IllegalThreadStateException
run() is an ordinary call on the current thread; start() asks Java for a new one.

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

WayCode
Extend Threadclass InvoiceMailer extends Thread { public void run() {...} }
Implement Runnablenew Thread(new ReportTask(...), "report-worker")
Lambdanew Thread(() -> {...}, "backup-worker")
Start itstart(), never run(), and only once

Next: making a thread wait with sleep, join and interrupt.

Keep going in Java · 66 of 79

Previous
Why Concurrency: Processes, Threads and the Main Thread in Java
Next post
Java Thread Lifecycle: sleep, join and interrupt
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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.

On this page

  • A class that is a worker
  • Only the job, handed to a Thread
  • A lambda as the job
  • start() opens a new lane, run() does not
  • Two cashiers, one job
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.