With JDK >=开发者_Go百科 1.5, should the preferred way to start a thread always be an Executor or Executor Service, or are there still reasons to prefer to use a Thread.start if you don't need what an ExecutorService provides?
For syncronized, I used to think that using the new Lock implemenations was preferred, until I was explained otherwise. So I'm wondering the same thing about Executors. Are they just a way of handling more complex cases, or should they be the standard choice?
Java Concurrency in Practice at least clearly states in section 6.2.:
The primary abstraction for task execution in the Java class libraries is not
Thread
, butExecutor
. [...]Using an Executor is usually the easiest path to implementing a producer-consumer design in your application.
Personally, since Java 5, I've completely left over Thread
and ThreadGroup
, as they provide way less customization and functionality than ExecutorService
.
When using ExecutorService
, I know I can use Callable
, I know I can (with a little overhead) schedule repeated tasks. As a consequence, I consider direct instantiation of Thread
objects deprecated code, as Vector
and Hashtable
are.
Writing correct multi-threaded code is very difficult. The beauty of the Executor framework is that it implements most of the heavy lifting that developers will encounter and only requires that you implement Callable or Future and program to the java.util.concurrent API. IMHO it results in much more readable code and presents many fewer opportunities to incorrectly implement it due to the complexity of properly managing threads.
精彩评论