views:

130

answers:

4

Hi I like to know which is more preferable to create a thread by extending thread class or by implementing Runnable interface.And Why ?

Thanks..

A: 

Runnable, because you are not adding specialized behavior to the Thread class - you are simply marking your logic as being able to be run as its own thread.

MetroidFan2002
+8  A: 

You should make it Runnable, and then add it to any of the existing thread pool classes. You are encapsulating your unit of work in the new class, and then using the thread to run it.

You would only extend Thread if you were doing something to the thread class itself, such as extending it with new functionality. I doubt that is the case.

An alternative would be to make a new class that was a composition of thread and your custom logic, e.g. it has a Thread inside and its own 'execute()' method where it schedules the thread and adds (this) as a work item, completely hidden from the outside... But in that case you would be making your class Runnable anyway, just providing a convenience method to make adding it to a thread easier.

Andrew Backer
+1  A: 

Instantiating Runnable gives a cleaner separation between your code and the implementation of threads. The Runnable interface simply states that you can run this code in a different thread.

Also, since you can implement many Interfaces but extend only one class, you can only provide your own superclass if you implement Runnable. If you extend Thread, you can not have any other superclass.

The only caveat with Runnable is that you need two objects, one instance of Thread to actually run the code and one of your implementation of Runnable to provide the code.

phisch
+1  A: 

If you extend Thread, you always have to call .start(), which starts a NEW thread, and executes the task.

If you make it Runnable, you can also do new Thread(runnable).start(), but you are not confined to that. You can recycle threads, thereby saving some resources like this:

ExecutorService recycleSingleThread = Executors.newSingleThreadExecutor();
service.execute(runnable);
service.execute(someOtherTask);

Put a bunch of your runnables in a list first and then execute them when you feel like executing them:

List<Runnable> todoList = new ArrayList<Runnable>();
Runnable fetchPaper = new Runnable("paper");
todoList.add(fetchPaper);
Runnable fetchMilk = new Runnable("milk");
todoList.add(fetchMilk);

//do something else or even return todoList...
ExecutorService recycleSingleThread = Executors.newSingleThreadExecutor();
for(Runnable task : todoList){
    recycleSingleThread.execute(task);
}

Or you can even do

runnable.run();

within your own thread.

Perhaps you could even save a runnable, de-serialize it afterwards and run it.
All these flexibility will not be present if you'd extend Thread.

Enno Shioji