Skip to content

Module 10 · Lambdas, Streams, Concurrency and JDBC — topic 3 of 5

Multithreading and Executors

Threads and the Runnable and Callable interfaces, starting and joining threads, thread states, ExecutorService thread pools, Futures, CompletableFuture and virtual threads (Java 21).

Beginner 20 min read·Lesson 37 of 39 in Java Programming

Learning objectives

  • Create and start threads with Runnable and lambdas, and wait for them with join
  • Submit tasks to an ExecutorService and collect results with Future
  • Explain when concurrency helps and what virtual threads are

Definition

A thread is an independent path of execution within a program. Multithreading runs several threads concurrently so that work can overlap — using several CPU cores, or continuing while waiting for I/O. An ExecutorService manages a pool of threads that execute submitted tasks.

Introduction

A web server handles thousands of requests at once; a desktop app stays responsive while it downloads a file; a data job uses all eight cores to finish eight times faster. All of these rely on threads. Java has supported threads since version 1.0, and modern Java adds higher-level tools that make them far easier to use correctly.

Why it matters

Server-side Java is fundamentally concurrent, and concurrency questions appear in most backend interviews.

Using several cores can turn a slow batch job into a fast one.

Detailed explanation

Creating threads. Pass a Runnable (a task with void run()) to new Thread(task) and call start(). start creates a new thread that calls run; calling run() directly just runs the code in the current thread.

Waiting. t.join() blocks until thread t finishes. Without joins, main may finish (or print) before the worker threads do. Thread.sleep(ms) pauses the current thread; both throw the checked InterruptedException.

Scheduling is unpredictable. The order in which runnable threads execute is chosen by the operating system. Output from unsynchronised threads can interleave differently on every run — programs must not depend on it.

Thread states. NEW → RUNNABLE → (BLOCKED / WAITING / TIMED_WAITING) → TERMINATED.

Executors. Creating a thread per task is expensive. ExecutorService pool = Executors.newFixedThreadPool(4) reuses a fixed set of threads. submit(callable) returns a Future<T>; future.get() waits for the result. invokeAll runs a list of tasks. Always shutdown() the pool (or use try-with-resources on Java 19+, where ExecutorService is AutoCloseable).

Callable<T> is like Runnable but returns a value and may throw checked exceptions.

CompletableFuture composes asynchronous steps: supplyAsync(...).thenApply(...).thenCombine(...).

Virtual threads (Java 21) are lightweight threads managed by the JVM: Executors.newVirtualThreadPerTaskExecutor() can run hundreds of thousands of blocking tasks (such as network calls) cheaply. Platform threads remain best for CPU-heavy work.

Syntax

Java
Thread t = new Thread(() -> System.out.println("hello from a thread"));
t.start(); // run concurrently
t.join(); // wait for it to finish
try (ExecutorService pool = Executors.newFixedThreadPool(4)) { // Java 19+
Future<Integer> f = pool.submit(() -> 6 * 7);
System.out.println(f.get());
}
CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> "data").thenApply(String::toUpperCase);
  • Call start(), not run(), to create a new thread.
  • join() and get() wait; sleep() pauses; all can be interrupted.
  • Never rely on the order in which unsynchronised threads print.

Code examples

Starting and joining threads

Java
public class Main {
public static void main(String[] args) throws InterruptedException {
int[] results = new int[3];
Thread[] workers = new Thread[3];
for (int i = 0; i < 3; i++) {
final int id = i;
workers[i] = new Thread(() -> {
int sum = 0;
for (int n = id * 1000 + 1; n <= (id + 1) * 1000; n++) sum += n;
results[id] = sum; // each thread writes its own slot
}, "worker-" + i);
}
for (Thread t : workers) t.start();
for (Thread t : workers) t.join(); // wait for all of them
for (int i = 0; i < 3; i++) System.out.println(workers[i].getName() + " summed " + results[i]);
System.out.println("total " + (results[0] + results[1] + results[2]) + ", state of worker-0: " + workers[0].getState());
}
}
Output
worker-0 summed 500500
worker-1 summed 1500500
worker-2 summed 2500500
total 4501500, state of worker-0: TERMINATED

The threads may finish in any order, but the program prints only after join, in a fixed order, so its output is always the same.

start() versus run()

Java
public class Main {
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> System.out.println("task runs on: " + (Thread.currentThread().getName().equals("main") ? "main thread" : "a new thread"));
Thread t1 = new Thread(task);
t1.run(); // just a method call
Thread t2 = new Thread(task);
t2.start(); // a real new thread
t2.join();
}
}
Output
task runs on: main thread
task runs on: a new thread

More examples

Thread pools, Futures and CompletableFuture

Java
import java.util.*;
import java.util.concurrent.*;
public class Main {
static boolean isPrime(int n) {
if (n < 2) return false;
for (int d = 2; (long) d * d <= n; d++) if (n % d == 0) return false;
return true;
}
public static void main(String[] args) throws Exception {
int chunks = 4, limit = 200_000;
List<Callable<Integer>> tasks = new ArrayList<>();
for (int c = 0; c < chunks; c++) {
int from = c * limit / chunks, to = (c + 1) * limit / chunks;
tasks.add(() -> {
int count = 0;
for (int n = from; n < to; n++) if (isPrime(n)) count++;
return count;
});
}
try (ExecutorService pool = Executors.newFixedThreadPool(chunks)) {
List<Future<Integer>> futures = pool.invokeAll(tasks); // waits for all
int total = 0;
for (int c = 0; c < chunks; c++) {
int part = futures.get(c).get();
total += part;
System.out.println("chunk " + c + ": " + part + " primes");
}
System.out.println("primes below " + limit + ": " + total);
}
CompletableFuture<Integer> price = CompletableFuture.supplyAsync(() -> 1200);
CompletableFuture<Double> rate = CompletableFuture.supplyAsync(() -> 0.18);
String bill = price.thenCombine(rate, (p, r) -> p + p * r).thenApply(t -> "total with tax: " + Math.round(t)).get();
System.out.println(bill);
try (ExecutorService virtual = Executors.newVirtualThreadPerTaskExecutor()) { // Java 21
List<Future<String>> replies = new ArrayList<>();
for (int i = 1; i <= 3; i++) {
int id = i;
replies.add(virtual.submit(() -> { Thread.sleep(50); return "reply " + id; }));
}
for (Future<String> f : replies) System.out.println(f.get());
}
}
}
Output
chunk 0: 5133 primes
chunk 1: 4459 primes
chunk 2: 4256 primes
chunk 3: 4136 primes
primes below 200000: 17984
total with tax: 1416
reply 1
reply 2
reply 3

Step-by-step explanation

  • The range 0–200,000 is split into four chunks, each counted by a Callable<Integer> that returns its result.
  • invokeAll submits all tasks to a pool of four threads and waits until they are done, returning Futures in the same order as the tasks.
  • futures.get(c).get() retrieves each result; printing them in task order keeps the output deterministic even though the chunks ran in parallel.
  • thenCombine waits for two asynchronous values and merges them; thenApply transforms the combined result.
  • The virtual-thread executor runs each blocking task (sleeping 50 ms) on its own lightweight thread; the try-with-resources block waits for them and shuts the executor down.

Expected output

Running “Thread pools, Futures and CompletableFuture” prints exactly:

TextOutput
chunk 0: 5133 primes
chunk 1: 4459 primes
chunk 2: 4256 primes
chunk 3: 4136 primes
primes below 200000: 17984
total with tax: 1416
reply 1
reply 2
reply 3

Practical applications

  • Web servers handling many requests concurrently
  • Parallel batch processing of files, images or reports
  • Calling several remote services at once and combining their answers
  • Background tasks such as autosave and periodic clean-up

Best practices

  • Use executors instead of creating raw threads for many tasks.
  • Make tasks independent; return results rather than sharing variables.
  • Use virtual threads for many blocking I/O tasks and fixed pools sized to CPU cores for computation.

Common mistakes

Calling run() instead of start()

Avoid

new Thread(task).run(); // runs in the current thread

Prefer

new Thread(task).start();

run() is an ordinary method call; only start() creates a new thread of execution.

Forgetting to shut down an executor

Avoid

ExecutorService pool = Executors.newFixedThreadPool(4);
pool.submit(task); // JVM may never exit

Prefer

try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
pool.submit(task);
}

Pool threads keep the JVM alive; call shutdown() or, on Java 19+, use try-with-resources.

Important notes

  • ExecutorService became AutoCloseable in Java 19; virtual threads became standard in Java 21.
  • Timing-dependent output (such as which thread finishes first) varies between runs; the examples here only print results in a fixed order.

Key takeaways

  • start() runs a Runnable on a new thread; join() waits for it.
  • ExecutorService pools threads; submit returns a Future whose get() waits for the result.
  • CompletableFuture composes async steps; virtual threads make blocking tasks cheap.

Try it yourself

  1. 1
    Use a fixed thread pool to compute the sum of squares of 1..1,000,000 in four parts.
  2. 2
    Simulate downloading five files with sleep, first sequentially and then with an executor, and compare the elapsed time.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

4 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is the difference between calling t.start() and t.run() on a Thread?
  • ModerateWhat is printed?
  • AdvancedWhat is printed?
Practise this topic