Executor 框架分析

说明:本篇文章是在阅读《Java 并发编程艺术》过程中的一些笔记和分析,由于本人能力有限,如果有书写错误的地方,欢迎各位大佬批评指正!我们互相交流,学习,共同进步!

该项目的地址:https://github.com/xiaoheng1/concurrent-programming

1.Executor 框架的两级调度模型

在 HotSpot VM 的线程模型中,Java 线程(java.lang.Thread) 被一一映射为本地操作系统线程. Java 线程启动时会创建一个本地操作系统线程.
当该 Java 线程终止时,这个操作系统线程也会被回收.

Executor 调度任务,创建 java,lang.Thread, 而 java.lang.Thread 被映射为 OS 本地线程,受 OSKernel 调度.

Executor 是一个接口,它是 Executor 框架的基础,它将任务的提交与任务的执行分离开来.

public interface Executor {

/**
 * Executes the given command at some time in the future.  The command
 * may execute in a new thread, in a pooled thread, or in the calling
 * thread, at the discretion of the {@code Executor} implementation.
 *
 * @param command the runnable task
 * @throws RejectedExecutionException if this task cannot be
 * accepted for execution
 * @throws NullPointerException if command is null
 */
void execute(Runnable command);

}

ThreadPoolExecutor 是线程池的核心实现类,用来执行被提交的任务.

ScheduledThreadPoolExecutor 是一个实现类,可以在给定的延迟后运行命令,或者定期执行命令.

Future 接口相当于一个占位符,用于异步计算.

ThreadPoolExecutor 通常使用工厂类 Executors 来创建. Executors 可以创建 3 种类型的 ThreadPoolExecutor:
(1)SingleThreadPoolExecutor
(2)FixedThreadPoolExecutor
(3)CachedThreadPool

public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue()));
}

public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue());
}

CachedThreadPool 是大小无界的线程池,适用于执行很多的短期异步任务的小程序,或者负载教轻的服务器.

public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue());
}

2.ScheduledThreadPoolExecutor
ScheduledThreadPoolExecutor 继承自 ThreadPoolExecutor,它主要用来在给定的延迟时间之后运行任务,或者定期执行任务.
ScheduledThreadPoolExecutor 的功能与 Timer 类似,但功能比 Timer 更加强大.

3.FutureTask

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值