A thread is the course or path followed while a program is being run. The main thread, which is typically present in all programs, is provided by the JVM, or Java Virtual Machine, at the beginning of the program's execution. In this article, we will talk more about the threads in Java, the creation of a thread in Java, and ways to monitor a thread along with the life cycle of a java thread. We will also talk about various states that a thread goes in during the whole process.
A program can perform several tasks at once more effectively by using threads. Complex tasks can be carried out in the background using threads without interfering with the main program. Implementing an interface and extending a class are the two steps required to create a thread in Java. Java's java.lang library creates and manages every thread. thread type.
A single-threaded Java application can only handle one task at a time and contains just one Java thread. Multi-threading is the process of handling many tasks concurrently by creating numerous Java threads, each of which handles a different task.
There is a class called "thread" that offers constructors and methods for creating and managing threads. Extending the Object class, the Thread class implements the Runnable interface. The majority of commercial Java applications heavily rely on multithreading. The following instances of multi-threads will demonstrate why this is done for various reasons:
Wish to make a career in the world of JBPM? Start with HKR'S JBPM Training !
The JMX interfaces offered by contemporary JVMs enable monitoring tools to keep track of thread activity within the JVM. We should monitor threads in Java for the following purposes:
Wish to make a career in the world of Java? Start with HKR'S Java Training!
Implementing the runnable interface and overriding the run() method allows you to create threads. The start() method can then be called after creating a thread object.
There are 2 major ways of creating a thread:
Constructors and methods for starting and managing threads are available in the Thread class. The thread implements the Runnable interface and extends the Object.
The Runnable interface should be implemented by any classes that have instances that are meant to be executed by threads. The run() method is the only one available for the Runnable interface.
Let us see the benefits of creating threads below:
The usual error is to use the run() method to start a thread instead of the start() method.
import java.io.*;
class ABC extends Thread {
public void run()
{
System.out.print("Welcome to HKR Training");
}
public static void main(String[] args)
{
ABC x = new ABC();
x.start();
}
}
The output of the Java code is:
Welcome to HKR Training
import java.io.*;
class ABC implements Runnable {
public static void main(String args[])
{
ABC abc = new ABC();
Thread x = new Thread(abc, "Welcome");
x.start();
System.out.println(x.getName());
}
@Override public void run()
{
System.out.println("Inside run method");
}
}
The output of the Java code is:
Welcome
Inside run method
If you have any doubts on Java, then get them clarified from Java Industry experts on our Java Community
A thread can be in any of the following states in Java during its complete life cycle. These are the states:
1. New: A new thread is always in the new state when it is created. The function hasn't been run yet, thus it hasn't started to execute for a thread in the new state.
2. Active: A thread switches from the new state to the active state when it uses the start() method. The runnable state and the running state are both contained within the active state.
3. Waiting State: A thread is either in the blocked state or the waiting state whenever it is dormant for a while (but not forever). The task of the thread scheduler is to choose which threads to accept and which ones to refuse when there are many threads in the waiting or blocked state. The chosen thread is then given the chance to run.
4. Timed Waiting: Starvation can result from waiting. For instance, a thread (whose name is A) has entered a code's vital area and is unable to leave it. In this case, another thread (whose name is B) is forced to wait interminably, which causes it to starve. A timed waiting state is provided to thread B in order to prevent this occurrence. Therefore, the thread is only in the waiting state for a certain amount of time and not always. When we use the sleep() method on a particular thread, we are actually engaging in timed waiting. The thread enters the timed wait state using the sleep() function. The thread awakens when the allotted time has passed and resumes execution where it left off.
5. Terminated: A thread can enter the termination state for the reasons listed below:
A thread that has been terminated means it is no longer active in the system. In other words, the thread is inactive and cannot be revived (made active again after being killed).
The image below illustrates the states in the lifecycle of a thread:
Want to know more about Java, visit here Java Tutorial!
Using the Thread Class, which extends a Thread class that can implement the Runnable Interface and offers constructors to create as well as perform actions on a Thread, we can run threads in Java. We create the Thread using the following constructors:
import java.io.*;
import java.util.*;
public class HKR extends Thread {
public void run()
{
System.out.println("The thread has started running");
}
public static void main(String[] args)
{
HKR x = new HKR();
x.run();
}
}
The output of this java code is:
The thread has started running
import java.io.*;
import java.util.*;
public class HKR implements Runnable {
public void run()
{
System.out.println(
"The thread is successfully running");
}
public static void main(String[] args)
{
HKR x = new HKR();
Thread T= new Thread(x);
T.run();
}
}
The output of this java code is:
The thread is successfully running
import java.io.*;
import java.util.*;
public class HKR {
public static void main(String args[])
{
Thread T = new Thread("Hello Learners. Welcome to HKR!");
T.start();
String str = T.getName();
System.out.println(str);
}
}
The output of this java code is:
Hello Learners. Welcome to HKR!
import java.io.*;
import java.util.*;
public class HKR implements Runnable {
public void run()
{
System.out.println(
"The thread is ready and successfully running");
}
public static void main(String[] args)
{
Runnable x = new HKR();
Thread T = new Thread(x, "Thread");
T.run();
String s = T.getName();
System.out.println(s);
}
}
The output of this java code is:
The thread is ready and successfully running
Thread
Top 30 frequently asked JAVA Interview Questions!
Conclusion
In this article, we have talked about Java threads along with the creation of a thread in Java, and ways to monitor a thread along with the life cycle of a java thread. A program can perform several tasks at once more effectively by using threads. A thread is a course or path followed while running a program. The main thread, which is typically present in all programs, is provided by the JVM. We have also talked about various states that a thread goes in during the whole process such as new, runnable, terminated, etc
Related articles:
Batch starts on 2nd Jun 2023, Fast Track batch
Batch starts on 6th Jun 2023, Weekday batch
Batch starts on 10th Jun 2023, Weekend batch
Yes, Java is multi-threaded by nature. Numerous distinct threads may run concurrently and independently in a single Java program.
The start() function on the new Thread object must be called before the thread can begin to run after being formed by instantiating a Thread object or an object that extends Thread.
In Java, threads are used for everything that runs. Even if you don't explicitly call it, every program in the JVM world has at least one thread.
A program can perform numerous tasks at once more effectively because of threads.
A single-threaded Java application can only handle one task at a time and contains just one Java thread. Multi-threading is the process of handling many tasks concurrently by creating numerous Java threads, each of which handles a different task.