Friday, May 16, 2008

What are the ways of creating threads in Java and which method should we prefer?


There are two ways - one, by implementing the Runnable interface and two, by extending the Thread class.

Using Runnable interface: This interface has a single method 'run' and the programmer just need to put all the code which is required to be executed in the thread inside the definition of this method. Now the Runnable object is simply passed to the Thread constructor and the 'start' method of the Thread class is called to schedule the thread for execution.

public class SampleThreadUsingRunnable implements Runnable {

public void run(){
//... code which needs to be executed in the thread
}

public static void main(String [] args){
//...calling the start method to schedule the thread for execution(new Thread(new SampleThreadUsingRunnable())).start();

}

}

Using Thread class: An application can simply subclass the Thread class and provide the implementation of the 'run' method and then 'start' method can be called to schedule the execution.

public class SampleThreadUsingThread extends Thread {

public void run(){
//... code which needs to be executed in the thread
}

public static void main(String [] args){
//...calling the start method to schedule the thread for execution(new SampleThreadUsingThread()).start();
}

}

Which method should we prefer? - The choice mainly depends upon the use of the thread. Implementing Runnable interface provides little more flexibilty as the class still has a scope of subclassing any other class of its choice, whereas extending Thread class will obviously block that extra scope.

Extending Thread class is relatively easier to use and it may be slightly faster as it avoid an extra indirection which is inherently associated with the implementation of interfaces in Java. But, you'll hardly realize this difference on latest JVM implementations.



Share/Save/Bookmark


No comments: