What are Java Threads? Basically, Threads allows a program to operate more efficiently by doing multiple things at the same time.
To start the next task: Instead of waiting till one task ends, It will be more efficient to do multiple tasks at the same time.
The life cycle of a thread:
- New
- Runnable
- Running
- Non-Runnable (Blocked)
- Terminated The life cycle of Thread in detail:
1.New: The thread is in new state when you create an instance of Thread class. it is in this stare before the invocation of start() method.
2.Runnable: The thread is in runnable state after the invocation of start() method, but the thread scheduler has not selected it to be for running.
3.Running:
The thread is in running state when the thread scheduler has selected it.
4.None Runnable: In this state the thread is alive but not in running state .
5.Terminated: A thread is in terminated or dead state when it's run() method exits.
Creation of Threads:
There are two methods for creating threads: 1. Using Thread class
- Using Runnable Interface
In detail:
- Using Thread class: STEPS:-
i) Create a Thread class:
public class Myclass extends Thread
ii) Override run() method:
public void run();
iii) Create object of class:
MyThread obj = new MyThread();
iv)Invoke start() method:
obj.start();
- Using Runnable Interface: STEPS:
i) Create a thread class:
public class MyThread implements Runnable
ii) Override run() method:
public void run();
important point: We can also use '@override' to override the run()
iii) Create object of the class:
Thread t = new Thread(new MyThread());
Note: we use new twice because MyThread class does not extend Thread class
and we can also write the same thing as:
Runnable r = new MyThread();
Thread t = new Thread(r);
iv)Inoke start() method:
t.start();
Note: We use runnable interface because if a class is already a child of its parent class it cannot extend Thread class and hence it can implement Runnable Interface.
Similarities between Thread class and Runnable Interface:
- Both create a unique object of the class
- Both consumes more memory
- Both have to override the run() method
Top comments (0)