Friday, 25 November 2011

Creating Multiple Thread



Like creation of a single thread, You can also create more than one thread (multithreads) in a program using class Thread or implementing interface Runnable.

Example -1 

In this  example multiple threads are created by multiple object of same class.



class NewThread implements Runnable
{
  String name; // name of thread
Thread t;

  NewThread(String threadname)
  {
    name = threadname;
    t = new Thread(this, name);
    System.out.println("New thread: " + t);
    t.start(); // Start the thread
  }

  // This is the entry point for thread.
  public void run()
  {
    try
    {
      for(int i = 5; i > 0; i--)
      {
        System.out.println(name + "  :   " + i);
        Thread.sleep(500);
      }
    }
     catch (InterruptedException e)
     {
       System.out.println(name + "Interrupted");
     }
    System.out.println(name + " exiting.");
  }
}

class MultiThread
 {
  public static void main(String args[])
  {
    new NewThread("Thread One"); // start threads
    new NewThread("Thread Two");
    new NewThread("Thread Three");

    try
    {
            Thread.sleep(10000);
    }
    catch (InterruptedException e)
     {
       System.out.println("Main thread Interrupted");
     }

    System.out.println("Main thread exiting.");
  }
}

Example- 2
In this example multiple threads are created by using multiple class.

class A extends Thread
{
   public void run()
    {
         display();
    }
   void display()
    {
        System.out.println("Thread A");
        for(int i=0;i<5;i++)
         {
            System.out.println("Thread A -> No = " +i);
         }
      System.out.println("Exit from class A ");
   }
}

class B extends Thread
{
   public void run()
    {
         display();
    }
   void display()
    {
        System.out.println("Thread B");
        for(int i=0;i<5;i++)
         {
            System.out.println("Thread B ->No = " +i);
         }
      System.out.println("Exit from class B ");
   }
}

class C extends Thread
{
   public void run()
    {
         display();
    }
   void display()
    {
        System.out.println("Thread C");
        for(int i=0;i<5;i++)
         {
            System.out.println("Thread C ->No = " +i);
         }
      System.out.println("Exit from class C ");
   }
}

class MultiThread1
{
  public static void main(String args[])
   {
       A obja=new A();
       obja.start();

       B objb=new B();
       objb.start();

       C objc=new C();
       objc.start();
   }
}



Posted by :Ruchita Pandya

No comments:

Post a Comment