Example on Multithreading using implements method.

class CreateThread implements Runnable
{
String name;    // name of the thread to be created.
Thread print;  //Thread class reference variable.
   thread(String name)
{
  Thread print=new Thread(this,name);//creating thread object.
  this.name=name;
  System.out.println("new thread is: "+print.getName());//Printing the name of the thread .
  print.start();//this method create entry poin for the run method.
   }

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



for(int i=0;i<5;i++)
{
System.out.println("hey " +name+ " "+i);
Thread.sleep(1000);       //This line generate the interrupt exception . so must be cught.
}
}
catch(InterruptedException e)
{
System.out.println(e.getMessage());
}
}



}
class mainthread
{

public static void main(String[] args)
{
new CreateThread("hello");  //creating the object of the CreateThread class.
new CreateThread("dk ");
try{

Thread.sleep(10000);         //assuring that main class exist at the last.
}
catch(Exception e)
{
}
System.out.print("main thread ended");
}
}

No comments:

Post a Comment