Implementing Runnable vs. extending Thread

This question already has an answer here:

  • “implements Runnable” vs. “extends Thread” 40 answers

  • 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.


    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)


    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.

    链接地址: http://www.djcxy.com/p/92064.html

    上一篇: 线程与可运行

    下一篇: 实现Runnable与扩展Thread