❮ Previous Next ❯

Java Life Cycle Of Thread:

Thread has many different state throughout its life such as:

Thread should be in any one state of above and it can be move from one state to another by different methods and ways.

w3-example

t2.join();
t2.join(1000);
t2.join(1000,10);

here t2 is the thread object.then if t2 competes or if time expires or if waiting thread got interrupted, the thread will come out from the waiting state to ready state.

let's see a program using some thread methods such as yield(), sleep() method.

w3-example

class X extends Thread
{
public void run( )
{
for(int i=1;i<=4;i++)
{
if(i==2)
yield( );
System.out.println("in thread X : i="+i);
}
}
}
class Y extends Thread
{
public void run( )
{
for(int j=1;j<=4;j++)
{
System.out.println("in thread Y : j="+j);
}
}
}
class Z extends Thread
{
public void run( )
{
for(int k=1;k<=4;k++)
{
System.out.println("in thread Z : k="+k);
if(k==1)
try
{
sleep(1000);
}
catch(Exception e)
{
}
}
}
}
class TestMethods
{
public static void main(String[] args)
{
X ob1=new X( );
Y ob2=new Y( );
Z ob3=new Z( );
ob1.start( );
ob2.start( );
ob3.start( );
}
}
Output

in thread Y : j=1
in thread Z : k=1
in thread X : i=1
in thread Y : j=2
in thread X : i=2
in thread Y : j=3
in thread X : i=3
in thread Y : j=4
in thread X : i=4
in thread Z : k=2
in thread Z : k=3
in thread Z : k=4

It is pointed that sleep( ) method throws an exception. In this example, sleep( ) method is enclosed with in a try block and followed by a catch block.

❮ Previous Next ❯



  Tutorials

Popular Links

Contact Us

address Plot No-741,2ND Floor
Opp. Bhagabati Temple,Jayadev Vihar
      Bhubaneswar-751013
      Email: info@silantechnology.com
      Phone: 0674-2361252
address
39877, sundale dr, apt#101, Fremont, California 94538, USA
       Phone: +1(262)388-7619

facebook twitter google linked in

© 2018 Silan Technology. All Rights Reserved