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
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.