Last Updated on July 1, 2023 by Prepbytes
This article will study what threads are and how we can perform a thread program in JAVA. We will look at what threads are, and how they give an advantage over the normal processing technique, the life cycle or stages of a thread, and creating or running a thread program in JAVA using various techniques.
What is a Thread in Programming?
Threads can be assumed as subprocesses created to execute processes separately. Threads access shared memory with other threads but do not affect the working of other threads hence, they are independent in working states.
Advantages of using thread:-
- Threads are lightweight.
- Multiple threads can communicate with each other.
- Low cost as compared to the normal process approach
- Shared memory to execute the independent sub-processes.
- Effective for multi-tasking.
Thread Life Cycle
Thread can be classified into different stages it can lie in. The states are as follows:-
-
New State
This state is the default for a thread indicating that the execution is yet to be done. -
Active State
As the start() function is called, the thread gets switched into the active state. There are two sub-states within the active state that can be classified as:-- Runnable State – Threads in this state are ready to run and it’s the responsibility of the thread scheduler to allocate runnable threads an interval of thread time. Slices of intervals are shared among the existing threads of a program. In a matter, threads run for a slice of time and wait in the runnable state to turn into the running state on achieving the slice of time.
- Running State – The thread waits to transform into the running state from the runnable state until the Scheduler assigns them a slice of interval and switches back to the runnable state once the time is up.
-
Waiting State
The thread is in a blocked or waiting state while it is inactive on a temporary basis.
For. If P and Q are two threads with P having the access to resource A and Q waiting to get access to the same resource once P is done. Here, Q is in a blocked or waiting state and remains to be so until the task scheduler reactivates it.
In a condition, where both the threads have an equal slice of interval and both get to be in the blocked or waiting state then the task scheduler clears to process the queue. Thereby, rejecting any unnecessary threads and allocating processors on priority.
In case long waiting time, the risk of starvation is possible, where the threads waiting for the CPU keep on waiting for an undetermined amount of time. To avoid this, timed waiting is put into place every thread has a time period for the sleep() method called, and once the time period is over, the thread starts executing its task. -
Dead / Terminated State
The thread is terminated or dead when it completely performed its task or when it incompetently faces any errors, segmentation faults or exceptions etc.
Now that we know about threads and the life cycle of threads, we will be looking forward to how to do thread program in java in the further stages of this article.
Creation of Threads
There are two methods for the creation of threads in java:-
- Extendable Thread Class
- Runnable Interface
One of the ways to create a thread is by extending the thread class to include the required methods and operations performed on a Thread. The thread supports a runnable interface and has the following constructors in place for creation.
- Thread
- Thread (Runnable r)
- Thread (String name)
- Thread (String name, Runnable r)
Create Thread Program in Java (Extend Class)
class PrepBytes extends Thread{ public void run(){ System.out.println("Thread runs"); } public static void main(String[] args){ PrepBytes pb = new PrepBytes(); pb.run(); } }
Explanation: In the creation of a thread program in java, we are extending the Thread class with PrepBytes and defining the run method for the thread which is later being called after the object named pb initiated, to which the output is displayed:
Output
Thread runs
Create Thread Program in Java (Runnable Interface)
class PrepBytes implements Runnable{ public void run(){ System.out.println("Thread runs"); } public static void main(String args[]){ PrepBytes pb = new PrepBytes(); Thread tOne = new Thread(pb); // constructor Thread(Runnable r) is used here tOne.run(); } }
Explanation: The thread class is extended to use the class object as a thread object for which the created class object, pb is passed to the runnable constructor of the thread object. run() method is invoked as a result of which the output is printed.
Output
Thread runs
Thread Program in Java using Thread(String Name)
public class PrepBytes { public static void main(String argvs[]){ Thread tOne = new Thread("Thread String"); tOne.start(); String name = tOne.getName(); System.out.println(name); } }
Explanation: Class is defined wherein lies the thread object, created with thread data as a string and the thread starts using the start method. The name of the thread is extracted to a string-type variable that is further printed as result.
Output
Thread String
Create Thread Program in Java using Thread(
public class PrepBytes implements Runnable{ public void run(){ System.out.println("Thread is running"); } public static void main(String argvs[]){ Runnable rOne = new PrepBytes(); Thread tOne = new Thread(rOne, "Thread Runs"); tOne.start(); String name = tOne.getName(); System.out.println(name); } }
Explanation: An object of the class is created PrepBytes is created that is passed to the constructor of Thread class with the string name. The thread gets initiated using the start() method and an active state is enabled. Name of the thread is stored in the variable, name, which prints as the output
Output
Thread Runs
Thread is running
Conclusion
In this article, we got to know what threads are and how they behave along with the life cycle of a thread. We implemented a thread program in java using different techniques. We hope you liked this article focused on the thread program in java. Hope to see you back with another piece of information at PrepBytes.
Frequently Asked Questions (FAQs)
Q1. What are threads, and why are they advantageous in programming?
Threads in Java can be considered subprocesses that execute independently within a program. They allow for concurrent execution of tasks, enhancing performance and responsiveness. Threads provide advantages such as lightweight execution, enabling multiple threads to communicate with each other, efficient resource utilization, and effective multitasking.
Q2. What are the different stages in the life cycle of a thread?
Threads in Java go through various stages in their life cycle. These stages include the New state (when a thread is created but not yet started), the Runnable state (where a thread is ready to run but waiting for the CPU), the Running state (when a thread is actively executing its tasks), and the Waiting state (when a thread is temporarily inactive or waiting for a resource). Finally, a thread enters the Dead or Terminated state when it completes its task or encounters an error or exception.
Q3. How can I create a thread program in Java?
There are two common methods to create a thread in Java. The first method involves extending the Thread
class and overriding the run()
method with the desired tasks for the thread. The second method is by implementing the Runnable
interface and passing an instance of the implementation to a Thread
object. Both methods provide a way to define the thread’s behavior and start its execution using the start()
method.
Other Java Programs
Java Program to Add Two Numbers
Java Program to Check Prime Number
Java Program to Check Whether a Number is a Palindrome or Not
Java Program to Find the Factorial of a Number
Java Program to Reverse a Number
Java Program to search an element in a Linked List
Program to convert ArrayList to LinkedList in Java
Java Program to Reverse a linked list
Java Program to search an element in a Linked List
Anagram Program in Java
Inheritance Program in Java
Even Odd Program in Java
Hello World Program in Java
If else Program in Java
Binary Search Program in Java
Linear Search Program in Java
Menu Driven Program in Java
Package Program in Java
Leap Year Program in Java
Array Programs in Java
Linked List Program in Java
String Programs in Java
Star Program in Java
Number Pattern Program in Java
For Loop Program In Java
Pattern Program in Java
String Palindrome Program in Java