java | thread with runnable interface example


//Example creating Multiple thread using concept of implementing //Runnable interface

class NewThread implements Runnable
{
Thread t;
NewThread()
{
t=new Thread(this,"MyThread");
System.out.println("child thread= "+t);
t.start();// start() calls run() method
}
public void run()//overridden method
{
try{
for(int i=0;i<=5;i++)
{
System.out.println("child i= "+i);
t.sleep(1000);//suspended for 1 seconds
}
}
catch(InterruptedException e)
{

System.out.println("child Thread interrupted ");
}
System.out.println("child Thread Exiting ");
}
}

class ThreadDemo
{
public static void  main(String ar[])//main is a thread which start very first
{
new NewThread();
System.out.println("Current thread= "+Thread.currentThread());
try{
for(int i=0;i<=5;i++)
{
System.out.println("main i= "+i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("main Thread interrupted ");
}
System.out.println("Main Thread Exitting ");
}

}

Reactions:

0 comments:

Post a Comment