What is a Thread?
A thread is a light weight process.Java provides built in support for multithreading. A multithreaded program contain several parts than can run concurrently. Each part is a thread which has a separate thread of execution. A thread exists within a process and a single process can contain multiple threads.
Lifecycle of a Thread
A thread goes through various stages in its life cycle.Here’s the various states of a thread:-
- New :- When we create an instance of a thread ,its in a new state
- Runnable :- A thread is in runnable state after invocation of start method but it has not been selected by the schedular for execution.
- Running :- Java Thread is in running state.
- Blocked :- A thread can be in a blocked state waiting for a resource.
- Terminated :- A thread can be terminated which stops its execution.A thread cant be resumed after termination.
Threads can be created in two ways
- By extending thread class
- By implementing Runnable interface
Extending Thread class
Threads can be created by extending the Thread class .Here’s an example:-
Here we are extending the Thread class and overriding the run method .In the run method we define task/business logic to be executed in the thread.
Then we create the instance of our thread class and and start the thread.
Running the program results in the following output:-
The output may change every time you run the program depending on which thread is executed.
Implementing Runnable Interface
We can also create a thread by implementing the Runnable interface.
Then we create an instance of Runnable object (that’s our custom object) and pass this instance to the Thread object.
We start the thread using Thread start() method.
Please note that the output may vary every time you run the program .
That’s about creating and starting threads in Java.I hope you enjoyed reading this article. Happy Coding everyone 🙂