Search code examples
javamultithreadingconcurrencyrunnable

Understanding Java Concurrency with thread


I'm currently reading a java concurrency tutorial in http://tutorials.jenkov.com/java-concurrency/creating-and-starting-threads.html

I could not understand what following lines under "Subclass or Runnable?"

When having the Runnable's executed by a thread pool it is easy to queue up the Runnable instances until a thread from the pool is idle.


Solution

  • As the article points out they both "work", although in general, you should use Runnable (or if arguments/result are needed Callable with a Future) rather than subclassing Thread. As you noted, this is more flexible - it separates what is executed from whom is executing it. Extending Thread unnecessarily couples these two concepts tightly together in the same instance, breaking the OO principle of single responsibility.

    Occasionally you'll have to implement executable code as a subclass of Thread when your hand is forced by the API. For example, Runtime.addShutdownHook(Thread) requires that your code to be executed at shutdown is registered as a Thread instance. But if you're not dealing with one of these specific cases, then always use a Runnable.