February 7, 2024

Multithreading in Java Tutorial

You would have seen a lot of examples of multi-tasking where computer programs are handling more than one task at a time. For example- You can start a player and play songs while working on any editor and have a document of 100 pages getting printed at the same time. This is an example where separate processes are running concurrently. Same way with in the same program you can have several tasks running like in a song player you can start playing a song and at the same time click on "add song" button to add more songs to your playlist. With in a program these separate running tasks are called threads and this concept of dividing a program into separate sub-tasks to make it faster and more responsive is called multi-threading.

Multithreading in Java

Java is one of the first programming language to provide in-built support for multi-threading programming.

In Java multithreading the main class is Thread class, any thread in Java is an object of Thread class and the code that is executed by the thread is provided in the run() method of the Thread class. You will need to override the run() method and provide the required functionality.

Refer How to Create And Start Thread in Java to see the ways thread can be created in Java.

When a Java application starts you start with just one thread, called the Main Thread in Java. This thread has the ability to create additional threads, which can perform specific tasks. You will have to divide your application in such a way that separate sub-tasks can be performed by separate threads rather than main thread performing all the tasks.

Multithreading Java Example

Here is a Java program that shows creating a thread by implementing Runnable interface and also shows the main thread. Once you call the start() method of the thread you have created, it executes the run() method and displays the name of the thread. Once that thread is terminated control again goes to main thread whose name is also displayed.

class AnotherThread implements Runnable{
  @Override
  public void run() {
    System.out.println("run method of Another thread --" 
      + Thread.currentThread().getName());	
  }	
}

public class ThreadDemo {
  public static void main(String[] args) {
    Thread thread = new Thread(new AnotherThread(), "AnotherThread");
    thread.start();
    System.out.println("Main thread " + Thread.currentThread().getName());
  }
}
Output
Main thread main
run method of Another thread –AnotherThread

Life cycle of a thread in Java multithreading

In Java multithreading a thread can go through many states of existence. Once you call start() method on a thread it is in a runnable state. Once it starts running it can be suspended and the control given to another thread. A suspended thread can again resume its operation. A thread can also be in blocked state if it is waiting for a shared resource. Once thread has finished its operation it is terminated.

Refer Life Cycle of a Thread (Thread States) in Java to know more about thread states in Java.

Difference between thread and process

As stated in the beginning itself, in concurrent programming there are two types of multitasking-

  • Process based multitasking.
  • Thread based multitasking.

Though this tutorial is about multithreading in Java, for better understanding you should know the difference between thread and process in Java.

Thread Vs Process in Java
  1. A process has a self-contained execution environment. A process has its own run-time resources like memory space. Threads exist within a process — every process has at least one. Threads share the process's resources, including memory and open files.
  2. Processes are heavyweight tasks running in their own allocated memory space. Threads are lightweight spawned with in a process and share its memory.
  3. Processes are independent units with their own separate resources so inter-process communication is expensive. Threads share the resources with in a process so inter-thread communication is easy but at the same time require special attention to safe guard shared resources among threads.
  4. Context switching from one process to another is time-consuming as it is time consuming to save the state of the running process. Context switching among threads is not that time consuming.
multithreading in Java

That's all for the topic Multithreading in Java Tutorial. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment