Multithreading in Java with Example Program

In this tutorial, we will learn multithreading in Java with the help of real-time examples. Imagine today is your busy day where you have to do multiple tasks: cooking breakfast, sending emails, and listening to your favorite podcast, perhaps all at once.

If you tackled these tasks sequentially, it would consume a lot of time. However, managing all these tasks simultaneously can significantly save time.

Similarly, in the world of programming, Java is a multithreaded programming language, which means we can develop a multithreaded program using Java.

Multi-threading programming approach is one of the most powerful features of Java. It not only makes our program more responsive and interactive but also improves performance. Java uses a multithreading concept to handle several tasks simultaneously, making programs faster and more efficient.

Multithreading is like hiring a team of workers (threads) in your program, where each worker is responsible for handling a specific task.

For instance, when one thread waits for an email to be sent, the second one can be processing your breakfast, and yet the third one might be streaming your podcast. This way, none of the tasks have to wait for the others to finish before they start or continue, speeding up the overall process.

To grasp the concept of multithreading in Java, it’s essential first to understand the meaning of multithreading.

What is Multithreading in Java?


Multithreading means multiple threads of execution concurrently. The process of executing multiple threads simultaneously (concurrently) is called multithreading in Java.

In other words, multithreading is a technique or programming concept in which a program (process) is divided into two or more subprograms (subprocesses), each of which can perform different tasks simultaneously (at the same time and in parallel manner). Each subprogram of a program is called thread in Java.

Look at the below figure where a Java program has three threads, one main and two others. The other two threads, ThreadA and ThreadB are created and started from the main thread.


When a program contains multiple flows of control, it is called multithreaded program.Multithreaded program in Java

Once initiated by the main thread, thread ThreadA and ThreadB run simultaneously and share the resources together. It is the same as people living in a joint family and sharing certain resources among all of them.

Context Switch

When a program contains more than one thread, the CPU can switch between two threads to execute them at the same time. The switching between two threads is known as context switch.

The switching from one thread to another thread occurs so fast that it appears to the users that all threads are being executed at the same time. But in reality, only one thread is executed at a time.

Time Sharing

This technique is useful for those applications which need multiple tasks to be done simultaneously. In a single processor system, multiple threads share CPU time that is known as time-sharing.

The operating system is responsible for allocating and scheduling resources to them. Thus, multithreading improves the performance of CPU by maximum utilization and keeping the idle time of CPU to minimum.

In a multithreaded program, each thread is assigned a single task to perform and executes independently. If an exception occurs in one thread, it does not affect other threads during the execution.


For example, one thread read data, another thread process it, and third thread write it, thus improves the overall performance of an application.

We can write a multithreaded program to display animations, to play music, and download a file from the network at the same time.

Advantage of Multithreading in Java


The advantages of using multithreading programming concept are as follows:

  • In a multithreaded application program, different parts of the application are executed by different threads. The entire application does not stop even if an exception occurs in any of the threads. It does not affect other threads during the execution of the application.
  • Different threads are allotted to different processors and each thread is executed in different processors in parallel.
  • Multithreading helps to reduce computation time.
  • Multithreading technique improves the performance of the application.
  • Threads share the same memory address space. Hence, it saves memory.
  • Multithreaded program makes maximum utilization of CPU and keeping the idle time of CPU to minimum.
  • Context switching from one thread to another thread is less expensive than between processes.

Drawbacks of Multithreading in Java


The drawbacks of multithreading are as follows:

  • Increased complexity.
  • Synchronization of shared resources.
  • In the multithreading programming concept, debugging is difficult. At times, result is unpredictable.
  • Potential deadlocks.
  • Programming complications may occur.

Multitasking in Java


The process of executing one or more tasks concurrently or at the same time is called multitasking. It is the ability of an operating system to execute multiple tasks at once. The main purpose of multitasking is to use the idle time of CPU.

Multitasking can be implemented in two ways:

1. Process-based multitasking (Multiprocessing)
2. Thread-based multitasking (Multithreading)

Process-based Multitasking (Multiprocessing)


The process of executing multiple programs or processes at the same time (concurrently) is called process-based multitasking or program-based multitasking. In process-based multitasking, several programs are executed at the same time by the microprocessor.

Therefore, it is also called multiprocessing in Java. It is a heavyweight. A process-based multitasking feature allows to execute two or more programs concurrently on the computer.

A good example is, running spreadsheet program while also working with word-processor.

Each program (process) has its own address space in the memory. In other words, each program is allocated in a separate memory area.

The operating system requires some CPU time to switch from one program to another program. The switching of CPU among programs is called context switching.

The switching from one program to another program is so fast that it appears to the user that multiple tasks are being done at the same time.

Thread-based Multitasking (Multithreading)


A thread is a separate path of execution of code for each task within a program. In thread-based multitasking (also known as multithreading), a program uses multiple threads to perform one or more tasks at the same time by a processor.

This feature allows you to execute several parts of the same program at once because each thread in a multithreaded program has a different path of execution. This means that each thread can perform its task independently, without having to wait for other threads to complete their tasks.

Threads running concurrently allow multiple operations to proceed at the same time, which makes the program more efficient and gives better performance, especially in multi-code processors.

Realtime Example of Multithreading in Java


Let’s take different examples of thread-based multithreading in Java.

1. A very good example of thread-based multithreading is a word processing program that checks the spelling of words in a document while writing the document. This is possible only if each action is performed by a separate thread.

2. Another familiar example is a browser that starts rendering a web page while it is still downloading the rest of page.

Consider a program as shown in the below figure. The program is divided into two parts. These parts may represent two separate blocks of code or two separate methods that can perform two different tasks of the same program.Thread based multitasking (Multithreading) in Java

Hence, a processor will create two separate threads to execute these two parts simultaneously. Each thread acts as an individual process that will execute a separate block of code. Thus, a processor has two threads that will perform two different tasks at a time. This multitasking is called thread-based multiple tasking.

Advantage of Thread-based Multitasking over Process-Thread Multitasking


The main advantages of thread-based multitasking as compared to process-based tasking are

  • Threads share the same memory address space.
  • Context switching from one thread to another thread is less expensive than between processes.
  • The cost of communication between threads is relatively low.
  • Threads are lightweight as compared to processes (heavyweight). They utilize the minimum resources of the system. They take less memory and less processor time.

Java supports thread-based multitasking and provides a high quality of facilities for multithreading programming.

A great way to remember the difference between process-based multitasking and thread-based multitasking is process-based multitasking works with multiple programs or processes whereas thread-based multitasking works with parts of one program.

In process-based multitasking, a program is the smallest unit of executable code whereas, in thread-based multitasking, thread is the smallest unit of executable code.

Multithreading Example Program


Let’s take a very simple example program of multithreading in which we will create two threads using Thread class. This program will display a message on the console to demonstrate concurrent execution.

Example:

package multithreadingPrograms;
public class MyThread extends Thread {
 // Override the run() method to define the thread's task
    public void run() {
     // Using for loop to print numbers from 1 to 5.
        for (int i = 1; i <= 5; i++) {
         // Print the current thread's name and the current number
            System.out.println(Thread.currentThread().getName() + ": " + i);
            
            try {
             // Pause the thread for 500 milliseconds.
                Thread.sleep(500); // Sleep for 500 milliseconds
            } catch (InterruptedException e) {
                System.out.println(e); // Handle any interruptions.
            }
        }
    }
}
package multithreadingPrograms;
public class MultithreadingTest {
public static void main(String[] args) {
 // Creating two objects of MyThread.
    MyThread t1 = new MyThread();
    MyThread t2 = new MyThread();
        
 // Start the first thread.
    t1.start();
 // Start the second thread.
    t2.start();
  }
}
Output:
      Thread-1: 1
      Thread-0: 1
      Thread-1: 2
      Thread-0: 2
      Thread-0: 3
      Thread-1: 3
      Thread-0: 4
      Thread-1: 4
      Thread-0: 5
      Thread-1: 5

In this example program, we have created a class named MyThread that extends the Thread class to create a user-defined or custom thread. Then, we have overridden the run() method of Thread class to define the specific task that the thread will perform.

After that, we have used the for loop to print numbers from 1 to 5, indicating the demonstration of concurrent execution. The Thread.sleep(500) makes the thread pause for 500 milliseconds to simulate a delay between executions.

In the main() method, we have created two threads (t1 and t2) and started using the start() method, which internally calls the run() method. Both threads run concurrently, and displays messages independently.

When you run this program, both threads will print numbers from 1 to 5, but the order of output may vary because of the nature of multi-threading.


In this tutorial, you have learned the concepts of Java multithreading in depth through the help of realtime examples. I hope that you will have understood the basic definition of multithreading and multitasking in Java. If you get any errors in this tutorial, please inform our team through email. Your email will be precious to us.
Thanks for reading!!!