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.
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
.
The author just wants to convey that according to him Runnables are easier to use with thread pools. A concept of a thread pool is that you can have a fixed number of threads (say 10) waiting to take jobs. If all 10 of them are busy running threads, the outstanding work can be queued, until one of those threads from the pool is free.
Jenkov is highlighting, that choosing between Subclass or Runnable implementation is due to the preference if anything else.
He is referring to the thread pool pattern as an example why runnable interface implementation is more flexible. I support his original hypothesis, but mainly because the Runnable object can subclass a class other than Thread.
I don't quite see, how building thread pools would be that more cumbersome with subclasses of threads with java native libraries ie. java.util.concurrent.ThreadPoolExecutor. I wish Jenkov would have provided an example...
Jenkov goes further in his concurrency tutorial to describe fixed and cached thread pools using the ExecutorService factory methods. Take a look here: http://tutorials.jenkov.com/java-util-concurrent/executorservice.html. With the Java concurrency utilities that create these thread pools, using runnables is easier.
精彩评论