Prefer executors and tasks to threads

By using executor service, you can:
1. wait for a particular task to complete
2. wait for any or all of a collection of tasks to complete
3. wait for executor service's graceful termination to complete
4. retrieve the results of tasks one by one as they complete

Choosing the executor service for a particular application can be tricky.
If you're writing a small program, or a lightly loaded server, using Executors.newCachedThreadPool is generally a good choice, as it demands no configuration and generally "does the right thing".

In a heavily loaded production server, you are much better off using Executors.newFixedThreadPool, which gives you a pool with a fixed number of threads, or using the ThreadPoolExecutor class directly, for maximum control.

Not only should you refrain from writing your own work queues, but you should generally refrain from working directly with threads. The key abstraction is no longer Thread, which served as both the unit of work and the mechanism for executing it. Now the unit of work and mechanishm are separate. The key abstraction is the unit of work, which is called a task. There are two kinds of tasks: Runnable and its close cousin, Callable. The general mechanism for executing tasks is the executor serivce. If you think in terms of tasks and let an executor service execute them for you, you gain great flexibility in term of selecting appropriate execution policies. In essence, the Executor Framework does for execution what the Collections Framework did for aggregation.

你可能感兴趣的:(Executors)