The IoT Academy Blog

An Introduction to Thread in Java

  • Written By  

  • Published on October 28th, 2022

Table of Contents [show]

Introduction

 

Almost all operating systems support the idea of processes, which are independent running applications that are largely segregated from one another.

A tool called threading enables numerous tasks to coexist within a single process. Threads are supported by the majority of contemporary operating systems, and they have been around in various incarnations for a long time. As opposed to considering threads as an underlying operating system mechanism, Java is the first widely used programming language to explicitly embed threading within the language.

 

What is a thread in Java?

The path or direction followed while a programme is being executed is referred to as a thread in Java. At the beginning of programme execution, the JVM, or Java Virtual Machine, provides all programmes with at least one thread, known as the main thread. The main() method is invoked by the main thread when it is supplied.

A thread is a running thread in a program. An application on a Java Virtual Machine can run multiple startup threads concurrently. The priority of each thread is different. Higher-priority threads are executed before lower-priority threads.

Because it allows for numerous operations to be performed within a single procedure, a thread is essential to a programme. A program's threads frequently each have their own local variables, stacks, and programme counters.

 

Our Learners Also Read: What Makes Java the Best Among Other Programming Languages?

 

Why use Thread?

Use of threads in Java programmes is recommended for a variety of reasons. Unknowingly, you may already be using threads if you utilise Swing, servlets, RMI, or Enterprise JavaBeans (EJB).a
Some of the reasons for using fibers are that they can help:

• Make the user interface more responsive
• Take advantage of multiprocessor systems
• Simplify modeling
• Do asynchronous or background processing

 

The life cycle of a thread in Java

In Java, the term "thread life cycle" refers to the state changes that occur throughout a thread's existence, from birth to death. 
A thread instance enters the runnable state after being created and launched by using the start() function of the Thread class. 
The thread enters non-runnable mode when the sleep() or wait() methods of the Thread class are used.

In order to begin executing the command, the thread transitions back from the non-runnable state to the runnable state. 

When a thread leaves the run() process, it ends in death. 
The thread life cycle is the name given to these changes in thread state in Java.

The life cycle of thread essentially consists of the following 4 phases:

• New
• Executable/Run
• Blocked (unable to start status)
• Dead

 

A new state

The thread is created and declared as being in the New state when we utilise the Thread class to establish a thread entity. 
A thread enters a new state when it is created, even though the start() method on the instance has not yet been used.

 

Runnable State

A thread in the runnable state is ready to run code. When the new thread's start() function is called, it enters the runnable state.
In the executable environment, a thread is ready to run and waits for processor availability (CPU time). A thread has entered the queue (queue) of threads waiting to execute.

 

Running status

Running denotes that the CPU has given the thread a time slot to begin execution. A thread joins the running state when it is chosen by the thread scheduler to run from the runnable state.

When the launcher is in the operating state, the CPU gives it thread time and initiates its runtime process. This is the situation where the thread is actively working. A thread can only enter the running state from the runnable state.

 

Blocked status

When a thread is active, i.e., the thread class object persists but cannot be selected for execution by the scheduler. It is now inactive.

 

Dead State

When a thread's run() function finishes executing statements, the thread automatically dies or enters a dead state. A thread is terminated or killed when it exits the run() process. When the stop() function is called, the thread dies.

 

Creating a thread

A thread is created by "creating or implementing" the Runnable Interface or extending the Thread class. These are the only two ways we can create a thread.

Let's dive into the details of both of these ways of creating a thread:

 

Thread class

The Thread class has several methods and constructors that allow us to perform various operations on the thread. The Thread class extends the Object class. The Object class implements the Runnable interface. The Thread class has the following constructors used to perform various operations.

• Thread()
• Thread (executable, string name)
• Thread (executable target)
• Thread ( ThreadGroup group, Executable target, String name )
• Thread ( ThreadGroup group, executable target )
• Thread ( ThreadGroup group, String name )
• Thread (ThreadGroup group, Runnable target, String name, long stackSize)

 

Runnable Interface (run() method)

The class whose instances the thread will run must implement the Runnable interface. A thread can execute an action using the run() function of the Runnable interface.

 

start() method.

The method is used to start the thread we just created. Starts a new thread with a new call stack. The thread's status switches from New to Runnable after the start() method has been called. when the thread receives the appropriate start time, calls the run() function.

To further understand how we can create a Java thread by extending the Thread class, let's look at an example:

ThreadExample1.java

 

1.    // Implementing runnable interface by extending Thread class  
2.    public class ThreadExample1 extends Thread {  
3.         // run() method to perform action for thread.   
4.         public void run()  
5.         {    
6.            int a= 10;  
7.            int b=12;  
8.            int result = a+b;  
9.            System.out.println("Thread started running..");  
10.            System.out.println("Sum of two numbers is: "+ result);  
11.         }  
12.         public static void main( String args[] )  
13.         {  
14.          // Creating an instance of the class extend Thread class  
15.            ThreadExample1 t1 = new ThreadExample1();  
16.            //calling start method to execute the run() method of the Thread class  
17.            t1.start();  
18.         }  
19.    }  

 

Multithreading in Java

Multithreading in Java is a technique for operating two or more threads concurrently to maximise CPU usage. Therefore, it is frequently referred to as concurrency in Java. Every thread crosses over into the others. Because multiple threads do not allocate different memory areas, it saves memory. Also, switching between threads takes less time.

In Java, multithreading improves the program structure by making it simpler and easier to navigate. These generalized threads can be used in high-end applications to easily change or improve the configuration of these complex structures.

 

Conclusion

The main thread is the only thread that every Java programme possesses. The main() function of a Java programme is called when the JVM establishes a main thread and executes the programme.

Other threads that are created by the JVM but are largely invisible to you include threads for trash collection, object finalisation, and other JVM management activities. The Abstract Windowing Toolkit (AWT) or Swing UI, servlet containers, application servers, and Remote Method Invocation are examples of other devices that produce threads (RMI).
 

 

About The Author:

logo

Digital Marketing Course

₹ 9,999/-Included 18% GST

Buy Course
  • Overview of Digital Marketing
  • SEO Basic Concepts
  • SMM and PPC Basics
  • Content and Email Marketing
  • Website Design
  • Free Certification

₹ 29,999/-Included 18% GST

Buy Course
  • Fundamentals of Digital Marketing
  • Core SEO, SMM, and SMO
  • Google Ads and Meta Ads
  • ORM & Content Marketing
  • 3 Month Internship
  • Free Certification
Trusted By
client icon trust pilot
1whatsapp