Ways to create a Thread:
You can create a Thread in two ways:
- By extending the Thread class.
- By implementing a Runnable Interface.
Thread class:
The Thread class provides constructors and methods to create and perform operations on a thread.
Runnable Interface:
Runnable Interfaces have only one method, named run(). The Runnable Interface should be performed by classes where their instances plan to be executed by a thread. public void run(): is used to perform the action for a Thread.
Starting a thread:
The start() method of a Thread class is used to start a newly created thread. It performs the following tasks:
- A new thread starts(with their stack).
- The Thread moves to the Runnable state from New state.
- The run() method will run when the Thread gets a chance.
Java Thread Example by extending Thread class:
Output:Extended Thread Class Example: thread is running...
Java Thread Example by implementing Runnable interface:
Output:Runnable Interface Example: thread is running...