Java Multithreading Explained

Multithreading in Java is a core mechanism that allows for the concurrent execution of two or more parts of a program to maximize CPU utilization. Each part, known as a thread, operates independently within the program, enabling complex applications to perform multiple tasks simultaneously.

Creating Threads in Java

There are two primary ways to create a thread in Java:

  1. By Extending the Thread Class: This involves creating a new class that extends the Thread class and overrides its run() method. The run() method defines the code executed by the thread.
  2. By Implementing the Runnable Interface: This approach requires creating a new class that implements the Runnable interface and defining the run() method. An instance of this class is then passed to a Thread object, which starts the thread.

Example 1: Extending the Thread Class

Creating and starting threads by subclassing Thread and overriding its run() method.

Code Explanation: This example demonstrates creating two threads by extending the Thread class. Each MyThread instance overrides the run() method, where custom behavior for the thread is defined. When start() is called, the JVM calls the run() method of these threads. The output shows the unique ID of each thread, illustrating that two separate threads are running concurrently.

Example 2: Instantiating and Starting Two Threads

Demonstration of concurrently running two threads using the Runnable interface.

Code Explanation: In this example, a Runnable task is defined as a lambda expression that prints numbers 1 to 5, along with the current thread’s ID. Two Thread objects are created with this task and started. The output demonstrates that both threads execute the same task concurrently, showcasing how to run parallel tasks using the Runnable interface.

Synchronization in Multithreading

Synchronization ensures safe access to shared resources by multiple threads.

Example: Synchronization

Incrementing a shared counter with synchronized methods to avoid data inconsistency.

Code Explanation: This synchronization example features a Counter class with a method increment() that increases a count. The method is marked synchronized to ensure that only one thread can execute it at a time, preventing race conditions. Two threads increment the counter 1000 times each. Because of synchronization, the final count reliably reaches 2000, demonstrating thread-safe operations on shared resources.


Through these examples, we’ve explored fundamental concepts of Java multithreading, including thread creation, execution, and synchronization. The explanations aim to clarify how threads are managed and synchronized in Java, providing a foundation for building efficient, concurrent applications. Understanding these principles is crucial for leveraging the full capabilities of Java multithreading in real-world applications.

Leave a Reply

Your email address will not be published. Required fields are marked *