Multithreading in Java
page 3 of 5
by Debjani Mallick
Feedback
Average Rating: 
Views (Total / Last 10 Days): 27105/ 60

Creating Child Threads

We can create child threads by:

·         Creating a class that implements Runnable (Runnable is an interface)

·         Creating a class which extends Thread class

To create child thread using Runnable interface:

·         First declare the class which implements Runnable

·         Declare an object reference of thread class as an instance of the implementing class

·         Invoke constructor of the thread class within the constructor of implementing class

The syntax of the constructor will be as follows.

Listing 2

Thread(this,string);

Invoke the start method to actually run the thread.

Define the run method.

Listing 3

import java.lang.*;
class myThread implements Runnable
{
  Thread t;
  public myThread();
  {
    t = new Thread(this, "child thread");
    System.out.println("Starting the child");
    t.start();
  }
  public void run()
  {
    Try
    {
      for (int i = 5; i > 0; i--)
      {
        System.out.println("Child Thread:" + i);
        Thread.sleep(1000);
      }
 
    }
    catch (InterruptedException e)
    {
      System.out.println();
    }
    System.out.println("Finishing the thread");
 
  }
}
 
class threadDemo
{
  myThread = new myThread();
  Try
  {
    for (int i = 5; i > 0; i--)
    {
      System.out.println("Main Thread:" + i);
      Thread.sleep(2000);
    }
  }
  catch (InterruptedException e)
  {
    System.out.println();
  }
  System.out.println("Finishing the thread");
}
}

To create child thread using Thread interface, insert the following.

Listing 4

import java.lang.*;
class myThread extends Thread
{
  public void run()
  {
    … … … … … … … … …
  }
}

This methodology should be implemented only if the class which needs to be executed does not require to be extended from another class ever.


View Entire Article

User Comments

Title: good   
Name: sathyaraj
Date: 2008-07-01 4:52:18 AM
Comment:
we learn more about multithreading .............
Title: Thread program not working   
Name: Thread program not working
Date: 2008-04-30 6:25:37 AM
Comment:
Listing 1
Thread program not working
Title: Very Nice   
Name: Ajit
Date: 2007-08-20 3:20:09 AM
Comment:
Keep Up
Title: Nice   
Name: Jonas
Date: 2007-08-15 10:48:08 AM
Comment:
Its a good piece of writing
Title: Good   
Name: Rocky
Date: 2007-08-14 10:37:54 PM
Comment:
Keep up the good work

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2021 ASPAlliance.com  |  Page Processed at 2021-11-29 10:27:16 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search