Java Thread Class
In this tutorial, we will learn about what is Java Thread Class, how to use it and importance of threads along with working examples of Thread class.
Thread Class
java.lang.Thread
is an inbuilt class comes with the Java Platform, which allows the developers to create or spawn a new thread or sub-process with in the application to achieve a maximum throughput and takes an advantage of the muti-core/muti-CPU processing system.
Thread Class is used for creating threads and this can be instantiated in two ways.
- Extending java.lang.Thread Class.
- Implementing the Runnable Interface.
By extending java.lang.Thread class:
New thread can be spawned by extending the java.lang.Thread and just a invoke the start method of the Thread class will spawn a new thread. Need to specify set of instructions which needs to be executed by a thread under overridden method of run.
Following example shows about extending and creation of thread.
public class CreationOfThread extends Thread { //Extended the Thread Class
public static void main(String[] args) {
Thread thread=new CreationOfThread(); // Instantiating the Thread Class with sub-class
thread.start();//Starting a new thread
}
public void run() //Overriding the run method of Thread Class
{
//set of instructions which needs to be executed by a new thread
System.out.println("New thread started Running");
}
}
Output:
New thread started Running
Implementing Runnable Interface:
java.lang.Thread
can be instantiated by passing Runnable
implemented class, this is the second way of creating threads, the following example will show creating a thread with implementing Runnable
Interface.
public class CreationOfThread implements Runnable {
// CreationOfThread class implements Runnable Interface
public static void main(String[] args) {
CreationOfThread cot = new CreationOfThread();
Thread thread = new Thread(cot);
// Passing the Runnable implemented class to java.lang.Thread class
thread.start();
}
public void run() {
System.out.println("New thread started Running using by Runnable Interface");
}
}
Output:
New thread started Running using by Runnable Interface
Note: In both the ways of creating threads must following by overriding the run()
method.
Apart from creation of threads using java.lang.Thread
class, other methods of it also provides greater a flexibility of identifying thread state, communication between threads and pausing the threads for specified period.
Conclusion
In this tutorial, we have covered what is a thread, ways of creating threads with the working examples.