Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is more advisable to create a thread by extending a Thread class or implementing Runnable? [duplicate]

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

Thanks..

like image 555
giri Avatar asked Mar 02 '10 21:03

giri


2 Answers

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.

like image 149
Andrew Avatar answered Oct 05 '22 04:10

Andrew


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.

like image 30
Enno Shioji Avatar answered Oct 05 '22 04:10

Enno Shioji