Programs

How To Create a Thread in Java? | Multithreading in Java

In this article, we will take a look at threading in Java and explore the mechanisms that make threading possible. 

Threading In Java

The threading feature in Java is a lightweight sub-process. It is considered to be the smallest unit of processing. It is a means to achieve multitasking in a program. It is a useful feature when it comes to games, animation, etc.

Java has in-built support for creating threads and multi-threads. This is a clever approach to minimizing inefficiencies and lugging by optimum utilisation of CPU space. In Java, this can be done in two ways: 

  1. Extend Thread Class, or
  2. Implement Runnable Interface

When more than one threads are executed simultaneously, it is called multithreading. This essentially allows multiple parts of a program to run concurrently, each part of a thread and each thread follows a distinct path to execution. 

Threads utilise shared memory space; memory is not allocated to each part, resulting in maximum usage of CPU. Further, changing contexts doesn’t take up much time. However, too many threads could engage your CPU in context-swiching and your execution could get delayed. 

Check out our free courses to get an edge over the competition

A Thread Can Exist In One Of The Following Six States

  1. NEW – as soon as a thread is created, it exists in the new state. It essentially means that the thread is yet to begin execution. 
  2. RUNNING – when a thread is being executed or is in line to be executed, it is in the running state.
  3. WAITING – a running thread is sometimes halted or suspended in order to allow another activity to occur. A non-time-out version of wait() or join() can suspend a thread from executing. Once, the action has occurred, a suspended thread is resumed.
  4. TIMED-WAITING – a running thread is sometimes temporarily halted or suspended for a specific duration. For example, when sleep() function called. 
  5. BLOCKED – when a suspended Java thread can’t acquire a particular resource, it is blocked and exists in the blocked state. 
  6. TERMINATED – when a thread completed its execution, it exists in the terminated state. However, you can terminate a thread at any time. 

Explore Our Software Development Free Courses

Check out upGrad’s Advanced Certification in Blockchain

Learn more about Java architecture and components.

Benefits of creating a thread in Java

There are several advantages to creating threads. Some of these are

  1. Since threads are independent, one execution doesn’t affect another even when they operate on shared memory space. This also means you can perform more than one operations simultaneously. 
  2. Threading is a form of multitasking and saves times.
  3. An error in one thread doesn’t affect another. 

Check out upGrad’s Advanced Certification in DevOps 

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

 

How to create a thread in Java? 

As discussed above, there are two ways to do this: Extend Thread Class, or Implement Runnable Interface

Thread Class

There are constructors and methods in the Thread class that allow you to perform operations, manage and keep track of the threads. It extends the Object class which then implements the companion Runnable interface. The constructors present in the thread class are :Thread(), Thread(String name), Thread(Runnable r), and Thread(Runnable r, String name).

Following are the methods and their descriptions

Method What is used for?
start() Starts execution
run() To run an action for a thread
sleep() Puts a thread to sleeps for a given duration
join() Wait until another thread is terminated
getPriority() To denote the priority of a given thread
setPriority() To alter the priority of a given thread
getName() To return the name of a epecified thread
setName() To change the name of specified thread
getId() To return the ID of a given thread
isAlive() To test if a thread is still existing in anyone the states
yield() Pauses a thread object execution to allow another thread(s) to run
suspend() To suspend a given thread
resume() To resume a thread from suspended state
stop() To stop a given thread
destroy() To destroy thread group and subgroups
interrupt() To cause an interruption in thread execution
isinterrupted() To test if a given thread execution is interrupted
interrupted() To test if the current thread execution is interrupted
activeCount() To return the coun of active threads in a thread group
holdLock() It returns true if and only if the current thread holds the monitor lock on the specified object.
getState() To determine the state of a given thread
setContextClassLoader() To set the context ClassLoader
getContextClassLoader() To return the context ClassLoader

In order to create a thread by extending the Thread class, first a class must be created that extends the java.lang.Thread class. This class is defined to override the run() method. Next, an object is created in the new class which is following by calling the start() method to begin thread execution.

Must Read: Pattern Programs in Java You Should Checkout

Explore our Popular Software Engineering Courses

Runnable Interface

This is the easiest way to create a thread. Only one method is required to implement the Runnable Interface: run()

In order to declare it, we write

public void run()

Inside run( ), we proceed to write the code to create a new thread. 

Enroll in Software Engineering Courses from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

In-Demand Software Development Skills

Thread Class vs Runnable Interface

Thread class prevents you from extending any other class. This is because multiple inheritance is not possible in Java. However, this is not the case when we implement the Runnable interface where you continue to extend other classes.

Extending Thread class makes several important methods accessible to you that enhance the functionality of a thread. For example,  yield(), stop(), isalive(), interrupt(). The Runnable interface has only method which is rather limiting. 

Read our Popular Articles related to Software Development

Wrapping up

If you’re interested to learn more about Java, full-stack software development, check out upGrad & IIIT-B’s Executive PG Program in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

What is thread synchronization in Java?

Java allows for multithreading, where multiple programs run parallelly while also being assigned to different execution points. While this is a time-saver, multithreading can also cause complications and increase functionality issues for the program. This could be because numerous threads are trying to retrieve resources from the same reserves. Thread synchronization assorts the resources through synchronization boxes. The boxes allow only one thread to access the resource at a time. This renders other threads to be temporarily blocked from reaching the resource. Thread synchronization helps in retaining the functionality of the threads. It balances the access to resources, thus avoiding performance issues.

What is a deadlock in multithreading?

Multithreading increases accessibility for threads with different goals to operate concurrently. This increases the time-efficiency and apt consumption of the Central Processing Unit (CPU). Multithreading enables the management of multiple tasks, which provides increased output from the program. Multithreading operates through synchronization blocks by locking a particular resource for one thread to avoid consistency issues. Deadlock is a situational anomaly that occurs when two threads try to access resources that are present with the other. E.g., thread A is trying to acquire thread B’s resource while it has the lock to the resource that thread B requires.

What are blocking methods in Java?

Blocking methods in Java are a collection of techniques that assist in the trouble-free processing of threads. Each thread within the system is assigned a goal. When a thread reaches the execution point, the program will block the thread, causing it to become immovable. This means that the thread can’t be displaced until it completes the necessary work assigned to it. Blocking renders the system's scalability to a minimum one thread is allowed to function at a time. This creates a deficit in the process's performance and leads to underused CPU power.

Want to share this article?

Land on Your Dream Job

Leave a comment

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

Our Popular Software Engineering Courses

Get Free Consultation

Leave a comment

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

×
Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks