[笔记]Executors框架

框架结构

  • 任务:Runnable和Callable
  • 任务的执行:Executor接口->ExecutorService接口
    • ThreadPoolExecutor
    • ScheduledThreadPoolExecutor
  • 异步计算的结果:Future接口->FutureTask类

ThreadPoolExecutor

new ThreadPoolExecutor(corePoolSize,maximumPoolSize,keepAliveTime,timeunit,runnableTaskQueue,handler)
  • corePoolSize: 预热到这个线程大小,不再创建新线程,就要放到runnableTaskQueue里面
  • maximumPoolSize:只有runnableTaskQueue满了,才会创建新线程,最大线程数不超过这个值
  • runnableTaskQueue: 任务队列
  • handler:饱和策略
    • AbortPolicy:直接抛弃

通常使用工厂类Executors创建:

1.FixedThreadPool:满足资源管理的需求,适合负载比较重的服务器

public static ExecutorService newFixedThreadPool(int nThreads)
public static ExecutorService newFixedThreadPool(int nThreads,ThreadFactory threadFactory)

源代码:

public static 

2.SingleThreadPool: 满足保证顺序的执行每个任务,并且在任意时间点,不会有多个线程是活动的场景

public static ExecutorService newSingleThreadPool()
public static ExecutorService newSingleThreadPool(ThreadFactory threadFactory)

3.CachedThreadPool:大小无界,适用于很多短期异步的小程序,或者是负载较轻的服务器

public static ExecutorService newCachedThreadPool()
public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory)

ScheduledThreadPoolExecutor

使用工厂类Executors创建
1.ScheduledThreadPoolExecutor:

public static ExecutorService newScheduledThreadPool(int nThreads)
public static ExecutorService newScheduledThreadPool(int nThreads,ThreadFactory threadFactory)

2.SingleThreadScheduledExecutor:

public static ExecutorService newSingleThreadScheduledExecutor()
public static ExecutorService newSingleThreadScheduledExecutor(ThreadFactory threadFactory)

Future接口

当我们把Runnable接口或者Callable接口submit给ThreadPoolExecutor时,会返回一个FutureTask对象,API:

<T> Future<T> submit(Callable<T> Task)
<T> Future<T> submit(Runnable Task,T result)
Future<?> submit(Runnable Task)

Runnable和Callable接口

Executors提供的:

public static Callable<Object> callable(Runnable task)
public static <T>Callable<T> callable(Runnable task,T Result)
<script type="text/javascript"> $(function () { $('pre.prettyprint code').each(function () { var lines = $(this).text().split('\n').length; var $numbering = $('<ul/>').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($('<li/>').text(i)); }; $numbering.fadeIn(1700); }); }); </script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值