CodeGym /Courses /JAVA 25 SELF /Introduction to multithreading: why it’s needed

Introduction to multithreading: why it’s needed

JAVA 25 SELF
Level 51 , Lesson 0
Available

1. What is a thread of execution (thread)

A thread as an independent line of work

In Java (and in programming in general), a thread of execution is an independent sequence of instructions that runs in parallel with other threads within a single program. Imagine a factory: each seamstress has her own workstation and task; she works independently, but together they contribute to the overall result.

By default, a Java program starts with one thread — the one that launches the main method. But nothing prevents us from creating additional threads so that different parts of the program run simultaneously.

Processes and threads: what’s the difference?

  • Process — a “heavyweight” unit of execution. Each process has its own memory space, its own variables, its own resources. Processes are completely isolated from each other — if one “breaks,” the others won’t be affected.
  • Thread — a “lightweight” unit of execution within a process. All threads of one process share memory and resources. This means they can easily exchange data (and, alas, can easily interfere with each other).

Analogy:
A process is a separate apartment: each has its own walls and occupants.
Threads are the occupants inside one apartment: each has their own tasks, but the kitchen and bathroom are shared.

What does it look like in Java?

When you run a program, the JVM creates at least one thread — the main one (main). But you can create new threads to run tasks in parallel.

2. Why multithreading is needed

Responsiveness: the UI must not “freeze”

Suppose you are writing a graphical program — for example, a text editor. The user clicked the “Save” button, and you started a long, tedious file write to disk. If you do all this in the main thread, the program window will “freeze”: the user won’t be able to click anything, the cursor won’t move, the interface won’t respond. If you save the file in a separate thread, the interface will remain responsive, and the user can even change their mind and close the program.

Real-life example:
You open a browser and start downloading a large file. If the browser didn’t use threads, you wouldn’t be able to open a new tab or scroll a page until the file finished downloading!

Parallel data processing

Suppose you have a list of a thousand files to process (for example, recompute hashes or replace text). Why not process them in parallel? Each thread takes its own file and works with it independently, and the entire job finishes several times faster.

Example:
A server handles requests from hundreds of clients. If the server did this in a single thread, the rest of the clients would wait forever for their turn. With threads, each request is processed independently!

Using multi-core processors

Modern processors are not a single “brain,” but a whole team (cores) that can work in parallel. If your program uses only one thread, the other cores are idle and play Minesweeper. If you run multiple threads, all cores are busy, and the program runs faster.

Fun fact:
Even your phone has multiple cores, and laptops and servers have dozens! Not using them all is like buying a bus and riding it alone.

3. Real-world examples

Area Multithreading example
File downloads Downloading multiple files simultaneously
User interface (UI) The app doesn’t “freeze” while loading/saving data
Servers Handling many network requests in parallel
Games Separate threads for physics, graphics, audio, AI
Messaging apps Receiving messages, sending files, updating the UI
Video processing Processing frames in parallel

Mini analogy:
A chef cooks soup, the oven bakes a pie in parallel, and a robot vacuum cleans the floor — all at the same time, and dinner is ready faster!

4. Potential challenges of multithreading

Race condition
When several threads modify the same variable at the same time, the result can be unpredictable. For example, if two threads increment a shared counter simultaneously, the final value may be incorrect. We’ll talk about this in more detail in one of the next lectures.

Synchronization
To keep threads from interfering with each other, you have to devise ways to “agree” on who can change data and when. This is called synchronization. There are special keywords and constructs for this (synchronized, locks, etc.), which we’ll discuss later.

Deadlock (mutual blocking)
Sometimes threads can “get along” so well that they wait for each other forever, and the program hangs. This is called a deadlock — and it’s one of the trickiest errors in multithreaded programming.

Debugging and testing
Bugs in multithreaded programs are very hard to catch: sometimes everything works, sometimes it doesn’t. Sometimes a bug shows up only on the server or on a user’s machine, while on your computer everything is perfect. This makes testing and debugging multithreaded code a real quest for a developer.

5. Brief overview: what a multithreaded program looks like

Example without threads:

public class Main {
    public static void main(String[] args) {
        // Count to 5
        for (int i = 1; i <= 5; i++) {
            System.out.println(i);
        }
        // Print letters
        for (char c = 'A'; c <= 'E'; c++) {
            System.out.println(c);
        }
    }
}

The output is always the same:

1
2
3
4
5
A
B
C
D
E

Example with threads:

public class Main {
    public static void main(String[] args) {
        Thread numbers = new Thread(() -> {
            for (int i = 1; i <= 5; i++) {
                System.out.println(i);
                try {
                    Thread.sleep(100); // Wait a bit
                } catch (InterruptedException e) {
                    // Ignore
                }
            }
        });

        Thread letters = new Thread(() -> {
            for (char c = 'A'; c <= 'E'; c++) {
                System.out.println(c);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    // Ignore
                }
            }
        });

        numbers.start();
        letters.start();
    }
}

The output will be interleaved:

1
A
2
B
3
C
4
D
5
E

or, if the threads “race,” the order may differ. The main point — both loops run in parallel!

6. Useful details

Visual diagram: how threads work together

+-------------------+     +-------------------+
|   Main thread     |     |   Second thread   |
+-------------------+     +-------------------+
| 1 | 2 | 3 | 4 | 5 |     | A | B | C | D | E |
+-------------------+     +-------------------+
        |                         |
        |      Both are working   |
        |      at the same time   |
        +-------------------------+

Where Java uses threads “under the hood”

  • Garbage Collector — a separate thread cleans up unused objects.
  • I/O threads — reading and writing files, network connections.
  • Servers and web applications — each client request is handled in a separate thread.
  • Timers, task schedulers — executing tasks on a schedule.

7. Common beginner mistakes

Mistake #1: Expecting threads to always speed up the program.
In reality, if you have a single-core machine or you organize the work poorly, multithreading can only slow execution due to contention and the overhead of switching between threads.

Mistake #2: Ignoring synchronization issues.
Many are sure: “I’m just starting two threads — what could possibly go wrong?” But if both threads change the same variable, the result can be completely unexpected.

Mistake #3: Using threads for everything.
You shouldn’t start a separate thread for every little thing. Threads are a resource, and too many of them can lead to slowdowns and even a program crash.

Mistake #4: No error handling.
Threads can throw exceptions (for example, when working with files or the network). If you don’t handle these errors, the program can crash or “hang.”

1
Task
JAVA 25 SELF, level 51, lesson 0
Locked
Identifying the Program's Main Character 🕵️‍♀️
Identifying the Program's Main Character 🕵️‍♀️
1
Task
JAVA 25 SELF, level 51, lesson 0
Locked
Instructions for the assistant robot 🤖
Instructions for the assistant robot 🤖
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION