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:
- Extend Thread Class, or
- 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
- 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.
- RUNNING – when a thread is being executed or is in line to be executed, it is in the running state.
- 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.
- TIMED-WAITING – a running thread is sometimes temporarily halted or suspended for a specific duration. For example, when sleep() function called.
- BLOCKED – when a suspended Java thread can’t acquire a particular resource, it is blocked and exists in the blocked state.
- 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
|Blockchain Technology||React for Beginners||Core Java Basics|
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
- 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.
- Threading is a form of multitasking and saves times.
- 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
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?|
|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
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
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.