Effective Java 68 Prefer executors and tasks to threads

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

   

   

转载于:https://www.cnblogs.com/haokaibo/p/prefer-executors-and-tasks-to-threads.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值