java | creating multiple thread

//Example creating multiple Threads

class NewThread implements Runnable
{
String name;
Thread t;
NewThread(String n)
{

name=n;

t=new Thread(this,n);
System.out.println("thread name = "+t);
t.start();// start() calls run() method
}

public void run()//overrided method
{
try{

for(int i=0;i<=5;i++)
{
System.out.println(name +" i= "+i);
Thread.sleep(1000);//suspended for 2 seconds
}
}
catch(InterruptedException e)
{

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





class ThreadDemo
{

public static void  main(String ar[])//main is a thread which start very first
{
// creating three threads


new NewThread("one");
new NewThread("two");
new NewThread("three");

System.out.println("Current thread= "+Thread.currentThread());
try{
for(int i=0;i<=5;i++)
{
System.out.println("main i= "+i);
Thread.sleep(3000);
}
}
catch(InterruptedException e)
{
System.out.println("main Thread interrupted ");
}
System.out.println("Main Thread Exitting ");
}

}

Reactions:

0 comments:

Post a Comment