Thread in java

A thread, in the context of Java, is the path followed when executing a program. All Java programs have at least one thread, known as the main thread, which is created by the Java Virtual Machine (JVM) at the program's start, when the main() method is invoked with the main thread. 



Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process.

Threads can be created by using two mechanisms : 

1)Extending the Thread class 
One way to create a thread is to create a new class that extends Thread, and then to create an instance of that class. The extending class must override the run() method, which is the entry point for the new thread. It must also call start() to begin execution of the new thread.


2)Implementing the Runnable Interface
Runnable interface of Java is present in the java.lang package. It is a type of functional interface that provides a primary template for objects that we want to implement using threads.

We know that there are two ways to start a new Thread: Extending the Thread class and implementing the Runnable interface. There is no need to extend or subclass a Thread class when we can perform a task by overriding only the run() method of the Runnable interface.

Hence the Runnable interface provides a way for a class to be active without extending the Thread class. We need to instantiate an object of the Thread and pass it in as the target.

We mostly implement the Runnable interface when using no other method than the run() method. The Runnable interface defines only one method run() with no arguments and holds the code that needs to be executed by the thread.

Thus the classes implementing the Runnable interface need to override the run() method.

Posted on by