码迷,mamicode.com
首页 > 编程语言 > 详细

Effective Java 68 Prefer executors and tasks to threads

时间:2014-05-05 23:32:44      阅读:389      评论:0      收藏:0      [点我收藏+]

标签:style   class   java   color   width   int   

Principle

The general mechanism for executing tasks is the executor service. If you think in terms of tasks and let an executor service execute them for you, you gain great flexibility in terms of selecting appropriate execution policies. In essence, the Executor Framework does for execution what the Collections Framework did for aggregation.

Exceutor Framework is a flexible interface-based task execution facility.

Creating work queue with Executor

ExecutorService executor = Executors.newSingleThreadExecutor();

executor.execute(runnable);

Here is how to tell the executor to terminate gracefully (if you fail to do this, it is likely that your VM will not exit):

executor.shutdown();

Usage of executor service

Usage

Utility

Wait for a particular task to complete.

"background thread SetObserver"

Wait for any or all of a collection of tasks to complete.

invokeAny or invokeAll methods

Wait for the executor service‘s graceful termination to complete.

awaitTermination method

Retrive the results of tasks one by one as they complete.

ExecutorCompletionService

Control every aspect of a thread pool‘s operation

ThreadPoolExecutor class

Small program or lightly loaded server (submitted tasks are not queued but immediately handed off to a thread for execution. If no threads are available, a new one is created. )

Executors.newCachedThreadPool

Heavily loaded production server

Executors.newFixedThreadPool

ThreadPoolExecutor

   

Thread pool (Fixed or variable service number of threads) .

   

Task - The key abstraction is the unit of work.

Task category

return value

Runnable

N

callable

Y

   

  

Multithread

Time accuracy for long running tasks

Grace recover on uncaught exception

java.util.Timer

N

N

N

ScheduledThreadPoolExecutor

Y

Y

Y

   

   

Effective Java 68 Prefer executors and tasks to threads,布布扣,bubuko.com

Effective Java 68 Prefer executors and tasks to threads

标签:style   class   java   color   width   int   

原文地址:http://www.cnblogs.com/haokaibo/p/prefer-executors-and-tasks-to-threads.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!