Monday, 4 April 2011

Core Java: Thread Forking

IMPLEMENTING RUNNABLE INTERFACE:

To implement Runnable, we must only implement the method called run( ), which is declared as follows:
public void run( )
Inside this method we have to code that constitute the new thread. It is the entry point for another, concurrent thread of execution within our program. This thread will end when run( ) returns. After declaring a class that implements Runnable interface, we should initiate the object of type Thread using one of its several constructors like:
Thread(Runnable threadOb, String threadName)
In this constructor, threadOb is an instance of a class that implements the Runnable interface. This defines where execution of the thread will begin. The name of the new thread is specified by threadName. After the new thread is created, we have to start the thread using start( ) method of Thread class, as it will not start automatically.

For example the following example illustrate the point:

class NewThread implements Runnable
{
Thread t;
NewThread()
{
t=new Thread(this, "MyThread");
System.out.println(t);
t.start();
}
public void run()
{
// Do sht...
System.out.println(" Exiting from the child thread");
}
}

EXTENDING THREAD CLASS:

The second way to create a thread is to create a new class that extends Thread, and then to create an instance of that class. The extending class must override the run( ) method. Here is the same program as above, rewritten to extend Thread:

class NewThread extends Thread
{
NewThread()
{
super("MyThread");
System.out.println(t);
start();
}
public void run()
{
// Do sht...
System.out.println(" Exiting from child thread");
}
}

N.B. if we are not overriding any of Thread’s other methods, it is probably the best approach simply to implement Runnable interface. Moreover that if the class has already been extended from another class then we have to implement Runnable interface.

No comments:

Post a Comment