I like to know which is more preferable to create a thread by extending thread class or by implementing Runnable interface.And Why ?
Thanks..
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With