欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Executor 框架

程序员文章站 2022-04-03 14:52:28
...
说明:本篇文章是在阅读《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<Runnable>()));
}
   
   
public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());
}


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

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

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

3.FutureTask