Friday 9 December 2016

java - Implementing Runnable vs. extending Thread




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


Answer



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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...