Prefer executors and tasks to threads

本文探讨了如何有效地使用Java的ExecutorService来管理线程池,包括任务执行、等待任务完成、优雅终止服务及任务结果的获取。重点介绍了在不同负载情况下的线程池选择策略,并阐述了如何通过分离任务执行与线程机制,实现更灵活的执行策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值