Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing Runnable vs. extending Thread [duplicate]

Tags:

java

Why is implementing Runnable a better option than extending from Thread class?

like image 867
abson Avatar asked May 06 '10 16:05

abson


3 Answers

The actual point to take away is that implements is ALWAYS preferred over extends on any questionable cases.

Extends binds two class files very closely and can cause some pretty hard to deal with code.

When I first "understood" OO programming I was extending EVERYTHING, but it turned my whole design into mush. Now I extend just the few things that clearly and obviously pass the "is-a" test and everything else is an interface...

Many many problems just stopped happening (Confusing multiple inheritance situations, time wasted refactoring hierarchies, the tendency to have "protected" variables then wonder why they are changing when you didn't change them in the current class, chaining requirements for constructors, figuring out how different inheritance-trees interact with each other, ...

It seems like every 3 years (for the last 20) I think I really "Get" programming and look back at the stupid things I did 3 years ago in shame... This was one of those instances (but from closer to 7 years ago at this point)

like image 126
Bill K Avatar answered Oct 23 '22 08:10

Bill K


This way you decouple the computation (the what) from the execution (the when and/or the how).

With Runnable or Callable, you can for instance submit many work/computation to an Executor which will take care to schedule the stuffs. Here is an excerpt form ExecutorService:

pool = Executors.newFixedThreadPool(poolSize);
...
pool.execute(new Handler(serverSocket.accept()));
...
class Handler implements Runnable {
    ...
 }

Using Runnable/Callable gives you more flexibility that using Threads directly.

like image 42
ewernli Avatar answered Oct 23 '22 08:10

ewernli


Because IS-A really isn't what you want. Your class wants to be Runnable, but IS-A Thread feels too strong. That's what inheritance is saying. You really just want to implement the run() method, not all the other attendent stuff in the Thread class.

This falls in line with Scott Meyers very good advice in "More Effective C++": Make non-leaf classes abstract. Substitute interfaces and you're spot on.

like image 40
duffymo Avatar answered Oct 23 '22 08:10

duffymo