During the life time if a thread, it can enter many
states as shown below:
Newborn State: When a thread object is created, it is born and
said to be in newborn state. The thread is not yet scheduled for running. One
of the following operations can be carried out in this state:
o Schedule it for running using start() method.
o Kill it using stop()
method.
Runnable State:Runnable state means that thread is ready for
execution and is waiting for the availability of the processor. That is, the
thread has joined the queue if threads that are waiting for execution.
Running State:Running means that the processor has given its time
to the thread for its execution. A running thread can be suspended or
relinquish its control in one of the following situations:
o It has been suspend()
method. A suspended method can be revived by using resume() method.
o It has been made to sleep(time) for a
specified period of time.
o It has told to wait until some event occurs. This is
done by using wait() method. It can
be restarted by using notify()
method.
Blocked State: A thread is said to be blocked when it is prevented
from entering into the Runnable state and subsequently the running state. This
happens when a thread is suspended, sleeping or waiting.
Dead State:A running thread ends its life when it has completed
executing its run() method. A thread
can be killed as soon as it is born, or while it is running or when it is in
blocked state by calling stop()
method.
Creating and Manipulating Thread:
class
A extends Thread
{
public
void run()
{
for(int
i=1;i<=5;i++)
{
if(i==1)
yield();
System.out.println("Thread
A is executing");
}
}
}
class
B extends Thread
{
public
void run()
{
for(int
j=1;j<=5;j++)
{
if(j==4)
stop();
System.out.println("Thread
B is executing");
}
}
}
class
C extends Thread
{
public
void run()
{
for(int
k=1;k<=5;k++)
{
if(k==1)
try
{
sleep(500);
}
catch(Exception
e){}
System.out.println("Thread
C is executing");
}
}
}
classThreadmethod
{
public
static void main(String args[])
{
A a= new A();
B b=new B();
C c=new C();
a.start();
b.start();
c.start();
}
}
Output:
Thread B is executing.
Thread B is executing.
Thread B is executing.
Thread A is executing.
Thread A is executing.
Thread A is executing.
Thread A is executing.
Thread A is executing.
Thread C is executing.
Thread C is executing.
Thread C is executing.
Thread C is executing.
Thread
C is executing.
No comments:
Write comments