Life Cycle of a Thread

At any time the thread is said to be in one of several thread states.

The thread when created will in the born state. The thread remains in this state until the thread start method is called this causes the thread to enter the ready state. The highest priority ready thread enters the running state when the system assigns a processor to the thread. A thread enters the dead state when its run method completes or the stop method is called for it a dead thread will eventually be disposed of by the system.

One common way for a running thread to enter the blocked state is when the thread issues an input/output request. In this case, a blocked thread cannot use a processor even if one is available. When running thread sleep method is called that thread enters the sleeping state. A sleeping thread becomes ready after designated sleep time expires.

When running thread suspend method is called, that thread enters the suspended state. A suspended thread becomes ready when its resume method is called by another thread. A suspended thread cannot use a processor even if one is available.

When a running thread calls wait method the thread enters a waiting state where it waits in a queue associated with the particular object on which waits was called. The first thread in the wait queue for a particular objects becomes ready on a call to notify issued by another thread associated with that object.

A Thread enters the dead state when its run method completes or its stop method is called.

Example

public class MyThread extends Thread
{
public void run()
{
int sleepTime=(int)(Math.random()*5000);
try
{
Thread.sleep(sleepTime);
}
catch(lnterruptdException e)
{
}
System.out.println("My name is "+getName());
System.out.println("I Slept for "+sleepTime+" milliseconds \n");
}
public static void main(String args[])
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
MyThread t3=new MyThread();
t1.start();
t2.start();
t3.start();
}
}

Output

My name is Thread-1
I Slept for 2281 milliseconds

My name is Thread-0
I Slept for 4105 milliseconds

My name is Thread-2
I Slept for 4340 milliseconds

It's very calm over here, why not leave a comment?

Leave a Reply