Lesson 11 / 11

Multithreading Basics

Creating a thread

Thread worker = new Thread(() -> {
    System.out.println("Running in a separate thread");
});
worker.start();

A thread is an independent path of execution running alongside your program’s main thread. Starting one lets your program do more than one thing at effectively the same time — useful for anything that shouldn’t block the rest of the program while it runs, like a background download.

Why concurrency needs care

When two threads modify the same variable at the same time, you can get a race condition — unpredictable results that depend on the precise, unrepeatable timing of both threads. synchronized prevents that by only letting one thread execute a given block of code at a time:

public synchronized void incrementScore() {
    score++;
}

Without synchronized here, two threads calling incrementScore() at nearly the same instant could both read the same starting value before either writes back the result — and the final score would be short by one increment, with no error message anywhere to explain why.

ExecutorService — the modern approach

ExecutorService pool = Executors.newFixedThreadPool(4);
pool.submit(() -> processTask());
pool.shutdown();

Rather than manually managing raw Thread objects, real production code typically hands work to an ExecutorService, which manages a reusable pool of threads for you and reuses them across many submitted tasks — creating a brand new thread for every single small task is expensive and doesn’t scale.

A word of caution

Multithreading is genuinely one of the harder topics in programming — bugs caused by race conditions can be intermittent and extremely difficult to reproduce. Treat this lesson as an introduction to the vocabulary and the basic tools, not a complete education; real concurrent systems deserve careful, dedicated study beyond what a single lesson can cover.

You’ve completed the course

From your first class to generics, streams, and multithreading — you now have a professional-level Java foundation. Take the certification assessment next, or apply to the Java Backend Development Internship to build something real.