Java 并发编程—— Executors 分析应用,阿里架构师深入讲解Java开发

return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue());
}

由于使用 SynchronousQueue 作为阻塞队列,所以它的特点是:当有空闲线程存活的时候,复用空闲线程,否则去创建新线程。

1.4 newScheduledThreadPool 方法

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}

public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}

ScheduledExecutorService 类多用于定时任务的场景。

总结

Executors 方法的本质就是封装 ThreadPoolExecutor 类,创造比较常用额线程池类。

2. Future、FutureTask 和 Callable

在上篇关于 ThreadPoolExecutor 的文章中提到 executre 方法执行 Runnable 任务,同时也提及到 submit 方法。

public Future submit(Callable task)

那么 FutureFutureTaskCallable 有什么用途呢?

2.1 Future

Future 用处就是对于具体的 Runnable 或者 Callable 任务的执行结果进行取消、查询是否完成、获取结果。必要时可以通过 get 方法获取执行结果,该方法会阻塞直到任务返回结果。

public interface Future {

/**

  • 尝试取消任务
  • 任务已经执行完成、已经被取消或者任务不能取消的状态时会返回false
  • 如果返回ture,并且task没有开始,则应该取消不执行。
  • 如果任务已经开始了,就由mayInterruptIfRunning参数决定是否打断
    */
    boolean cancel(boolean mayInterruptIfRunning);

/**

  • 如果在任务执行完成之前调用返回ture
    */
    boolean isCancelled();

/**

  • 任务完成返回true
    */
    boolean isDone();

/**

  • 等待执行完成获取结果
  • @return the computed result
  • @throws CancellationException if the computation was cancelled
  • @throws ExecutionException if the computation threw an
  • exception
  • @throws InterruptedException if the current thread was interrupted
  • while waiting
    */
    V get() throws InterruptedException, ExecutionException;

/**

  • 等待最多 timeout 时间来获取结果,指定时间内没完成获取到结果,返回null
  • @param timeout the maximum time to wait
  • @param unit the time unit of the timeout argument
  • @return the computed result
  • @throws CancellationException if the computation was cancelled
  • @throws ExecutionException if the computation threw an
  • exception
  • @throws InterruptedException if the current thread was interrupted
  • while waiting
  • @throws TimeoutException if the wait timed
  • 12
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值