Skip to main content

Introduction to Multithreading

In Java, Multithreading is a core feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such a program is called a thread.

Threads are lightweight sub-processes and the smallest unit of processing. Multithreading and multiprocessing are both used to achieve multitasking.


What is Multitasking?

Multitasking is the process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU efficiently. Multitasking can be achieved in two ways:

1. Process-based Multitasking (Multiprocessing)

  • Each process has its own address in memory (i.e., each process allocates a separate memory area).
  • A process is heavy-weight.
  • Cost of communication between processes is high.
  • Switching from one process to another requires some time for saving and loading registers, memory maps, updating lists, etc.

2. Thread-based Multitasking (Multithreading)

  • Threads share the same address space.
  • A thread is lightweight.
  • Cost of communication between threads is low.

[!NOTE] In Java, we heavily rely on Thread-based multitasking because it consumes less memory and is extremely fast to context-switch compared to process-based multitasking.


Advantages of Java Multithreading

  1. Does not block the user: It doesn't block the user because threads are independent, allowing you to perform multiple operations at the same time.
  2. Time-saving: You can perform many operations concurrently, which saves significant execution time, particularly in web applications or games.
  3. Independent execution: Threads are independent, meaning if an exception occurs in a single thread, it doesn't affect the execution of other threads.

What is a Thread in Java?

A thread is a lightweight sub-process. It is a separate path of execution.

Every Java program has at least one thread, known as the Main Thread, which is created by the JVM to execute the main() method. From this main thread, you can spawn multiple child threads.

In the next sections, we will explore exactly how to create these threads, manage their lifecycle, and synchronize them to prevent data conflicts.