Multithreading in Java

Multithreading in Java


In this blog, we will look at Threading in Java.We will cover the following topics in detail:

  • Introduction to Java Thread
  • The Java Thread Model
  • Creating & Using a Java Thread
  • Multithreading in Java



Introduction to Java Thread

When it comes to programming languages, Java is the only one that provides built-in support for multithreading. In a multithreaded programming environment, two or more programs can run concurrently. Each of these programs are called threads and are considered as the smallest unit of processing. During run-time, the threads in a given program exist in a common memory space and therefore share both data & code. However, each thread maintains an exclusive execution path. This enables the language to perform multitasking without having the heaviness of multiprocessing.


Java achieves threading through java.lang.Thread class. These are lightweight in nature and can run concurrently in synchronous or asynchronous mode.


We can classify threads into User-defined threads and Daemon threads.

(1) User-defined threads are those that are created programmatically by the user. These are high priority threads. The Java Thread Model (JVM) waits for these threads to finish.

(2) Daemon threads are created by the JVM.



The Java Thread Model

The Thread Model in Java has got a life-cycle with different stages as shown below:



  • New: A thread is said to be in a new state just after we initiate the instance of a new thread class.
  • Runnable: A thread becomes runnable after it gets started.
  • Running: When the Java thread is executing its task, it is said to be in a running state.
  • Suspended: When a thread is in this stage, its activity is temporarily suspended. This state can be resumed from the part where it left off.
  • Blocked: When a Java thread is waiting for a resource, we can keep it in the blocked state.
  • Terminated: This means that the execution of a thread is halted immediately at any given time. Once the thread is terminated, it cannot be resumed.



The following are some of the important Thread Methods that are used in managing a thread object.


  • public void start(): The start() starts the thread in a separate path of execution, after which it invokes the run() method, on this thread object.
  • public void run(): The run() method is invoked on a thread object that is instantiated using a separate runnable target.
  • public static void yield(): This method is used by a currently running thread to yield to any other threads of the same priority that are waiting to be scheduled.
  • public final void join(long millisecond): This method is invoked by a thread on a second thread, causing the first thread to be blocked until the second thread is terminated.
  • public static void sleep(long millisecond): This method causes the currently running thread to be blocked for the specified number of milliseconds.
  • public static void setName(): The setName() method sets the name of the thread to the value specified.
  • public static void is Alive(): This method returns a boolean value that indicates whether the current thread is alive or not.
  • public static void setPriority: The setPriority method changes the priority of the thread to the specified value.



Creating a Java Thread

In Java, two ways you can create a thread:

  1. Through implementing the Runnable Interface.
  2. Through extending the Thread Class.



1. Runnable Interface

A thread created by implementing Runnable Interface will execute the code defined in the public method run(). Sample code will look like the one given below:  



class SampleRunnable implements Runnable {

  private String threadName = “Runnable Interface

  Demo Thread”;

  public void run() {

    System.out.println(“Running ” + threadName );





Given code will create a thread that will print Runnable Interface Demo Thread during execution. Before that, we need to start the created thread, and for that, we pass an instance of our SampleRunnable Class into the constructor of the Thread class.



The code will look like this:



Thread sampleThread = new Thread(new SampleRunnable ());




2. Extending Thread Class

In this method we create a class that extends the Thread class and we override the existing run() method in it. Here in order to run the thread, we will create an instance of the class that extended the Thread Class.



public class SampleThreadClass extends Thread {

  private String threadName = “Thread Class Demo”;

  public void run() {

    System.out.println(“Running ” + threadName );





Inorder to run the above thread, we will do the following:



SampleThreadClass threadClass = new SampleThreadClass ();




This code when it gets executed will call run() and will print Thread Class Demo.



Multithreading in Java

When we have more than one thread in a Java program, it becomes a multithreaded program and at this point, there are some more things we have to be aware of. There may be a scenario where multiple threads try to access the same resource and finally they might produce a hang. In this kind of scenario, there is a need to synchronize the action of multiple threads and make sure that only one thread can access the resource at a given point in time. This is implemented using a concept called monitors. Java has a provision for creating threads and synchronizing their tasks by using synchronized blocks. This way, we can efficiently manage the resource allocation to multiple threads during execution. But at the same time, synchronization sometimes produces a case called dead-lock. It’s a situation where one thread waits for the second one to finish object lock, but the latter is waiting to release the object lock of the first thread. By structuring the code properly we can avoid such dead-lock situations.



End note:

We studied threads in Java. We also looked at two types of Java thread models and understood how the Java Thread Model (JVM) works. Additionally, we learned how to create the Java thread by using two methods, i.e. runnable interface and through extending the Thread class. Overall, we learned how the concept of thread is implemented in Java, and last but not the least, how multithreading works in Java.



Get one step closer to your dream job!



Prepare for your Java programming interview with Core Java Questions You’ll Most Likely Be Asked. This book has a whopping 290 technical interview questions on Java Collections: List, Queues, Stacks, and Declarations and access control in Java, Exceptional Handling, Wrapper class, Java Operators, Java 8 and Java 9, etc. and 77 behavioral interview questions crafted by industry experts and interviewers from various interview panels.



We’ve updated our blogs to reflect the latest changes in Java technologies.

This blog was previously uploaded on March 27th, 2020, and has been updated on January 4th,  2022.