1. New: In this state, a new thread begins its life cycle. This is also called a born thread. The thread is in the new state if you create an instance of Thread class but before the invocation of the start() method.
2. Runnable: A thread becomes runnable after a
newly born thread is started. The thread in runnable state joins the queue of threads waiting for processor.
A thread can be executed before its turn using yeild() method.
3. Running: When the thread scheduler selects
the thread then, that thread would be in a running state and execution of a thread starts.
A running thread can be suspended using suspend() method. A suspended thread can resume its execution using resume() method.
A running thread can be made to sleep for specific period of time using sleep(time) method, the thread enters suspend state. After given time is elapsed thread automatically enters into runnable state.
A running thread is made to wait using wait() method, it will be in wait state until an event is occurred. A waiting thread can be resumed using notify() method.
4. Blocked: The thread is still alive in this
state, but currently, it is not eligible to run.
5. Terminated: A thread is terminated due to the
following reasons:
- Either its run() method
exists normally, i.e., the thread’s code has executed the program.
- Or due to some unusual errors like segmentation fault or an unhandled exception.
Ex:
A1.java
class A1 extends Thread {
public void run() {
System.out.println("Thread A");
System.out.println("i in Thread A ");
for (int i = 1; i <=
5; i++) {
System.out.println("i = " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException
e) {
e.printStackTrace();
}
}
System.out.println("Thread A Completed.");
}
}
B1.java
class B1 extends Thread {
public void run() {
System.out.println("Thread B");
System.out.println("i in Thread B ");
for (int i = 1; i <=
5; i++) {
System.out.println("i = " + i);
}
System.out.println("Thread B Completed.");
}
}
ThreadLifeCycleDemo.Java
public class ThreadLifeCycleDemo {
public static void main(String[] args) {
A1 threadA = new A1();
B1 threadB = new B1();
threadA.start();
threadA.yield();
try {
threadA.sleep(1000);
} catch (InterruptedException
e) {
e.printStackTrace();
}
threadB.start();
System.out.println("Main Thread End");
}
}
No comments:
Post a Comment