java中线程池核心API源码分析

java中线程池核心API源码分析,第1张

java中线程池核心API源码分析

文章目录

概述源码分析

ExecutorExecutorServiceScheduledExecutorServiceThreadPoolExecutorScheduledThreadPoolExecutor

概述

线程池是一种多线程处理形式,处理过程中将任务添加到队列,然后在创建线程后自动启动这些任务。线程池线程都是后台线程。每个线程都使用默认的堆栈大小,以默认的优先级运行,并处于多线程单元中。如果某个线程在托管代码中空闲(如正在等待某个事件),则线程池将插入另一个辅助线程来使所有处理器保持繁忙。如果所有线程池线程都始终保持繁忙,但队列中包含挂起的工作,则线程池将在一段时间后创建另一个辅助线程但线程的数目永远不会超过最大值。超过最大值的线程可以排队,但他们要等到其他线程完成后才启动。

jdk中当然也提供了一些 *** 作线程池的API。

java中 *** 作线程池的api位于java.util.concurrent;包中。

常见的核心接口和实现类包括Executor接口、ExecutorService接口、ScheduledExecutorService接口、ThreadPoolExecutor实现类、ScheduledThreadPoolExecutor实现类等。

Executor接口
最上层的接口,定义了执行任务的execute()方法。

ExecutorService接口
继承了Executor接口,扩展了Callable、Future、关闭方法。

ScheduledExecutorService接口
继承了ExecutorService接口,增加了定时任务相关的方法。
ThreadPoolExecutor实现类
基础、标准的线程池实现。

ScheduledThreadPoolExecutor实现类
继承了ThreadPoolExecutor,实现了ScheduledExecutorService中定时任务相关的方法。

他们之间的继承实现关系图如下:

源码分析

下面对Executor接口、ExecutorService接口、ScheduledExecutorService接口、ThreadPoolExecutor实现类、ScheduledThreadPoolExecutor实现类这几个核心api的源码进行分析。

Executor
public interface Executor {

    
    void execute(Runnable command);
}

Executor是最上层的接口,该接口提供了一个execute()方法,用于执行指定的Runnable任务。

ExecutorService

ExecutorService接口继承至Executor接口,扩展了Callable、Future、关闭等方法。

public interface ExecutorService extends Executor

定义的方法

     //启动有序关闭,先前已经执行的的任务将会继续执行,但不会执行新的任务。
    void shutdown();

     //尝试停止所有主动执行的任务,停止等待任务的处理,并返回正在等待执行的任务列表。
    List shutdownNow();

     //如果这个Executor已被关闭,则返回 true 。 
    boolean isShutdown();

    //如果所有任务在关闭后完成,则返回true 。 请注意, isTerminated从不true ,除非shutdown或shutdownNow先被执行。 
    boolean isTerminated();

    //阻止所有任务在关闭请求完成后执行,或发生超时,或当前线程中断,以先到者为准。 
    boolean awaitTermination(long timeout, TimeUnit unit)
        throws InterruptedException;

    //提交值返回任务以执行,并返回代表任务待处理结果的Future。
     Future submit(Callable task);

    //提交一个可运行的任务执行,并返回一个表示该任务的Future。Future的get方法将在成功完成后返回给定的结果。
     Future submit(Runnable task, T result);

    提交一个可运行的任务执行,并返回一个表示该任务的Future。Future的get方法将在成功完成后返回null。
    Future submit(Runnable task);

    //执行给定的任务,返回持有他们的状态和结果的所有完成的Future列表。
     List> invokeAll(Collection> tasks)
        throws InterruptedException;

    //执行给定的任务,返回在所有完成或超时到期时持有其状态和结果的Future列表
     List> invokeAll(Collection> tasks,
                                  long timeout, TimeUnit unit)
        throws InterruptedException;

    //执行给定的任务,返回一个成功完成的结果(即没有抛出异常),如果有的话。 正常或异常退出后,尚未完成的任务将被取消。
     T invokeAny(Collection> tasks)
        throws InterruptedException, ExecutionException;

    //执行给定的任务,返回一个已经成功完成的结果(即,不抛出异常),如果有的话。
     T invokeAny(Collection> tasks,
                    long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
ScheduledExecutorService

ScheduledExecutorService接口继承了ExecutorService接口,增加了定时任务相关的方法。

public interface ScheduledExecutorService extends ExecutorService

方法

     
    public ScheduledFuture schedule(Runnable command,
                                       long delay, TimeUnit unit);

    
    public  ScheduledFuture schedule(Callable callable,
                                           long delay, TimeUnit unit);

    
    public ScheduledFuture scheduleAtFixedRate(Runnable command,
                                                  long initialDelay,
                                                  long period,
                                                  TimeUnit unit);

    
    public ScheduledFuture scheduleWithFixedDelay(Runnable command,
                                                     long initialDelay,
                                                     long delay,
                                                     TimeUnit unit);
ThreadPoolExecutor

ThreadPoolExecutor是一个基础、标准的线程池实现。

ThreadPoolExecutor中提供了四种构造函数以创建线程池。

参数的定义如下:

    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);
    }
/

    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue workQueue,
                              ThreadFactory threadFactory) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             threadFactory, defaultHandler);
    }

/
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue workQueue,
                              RejectedExecutionHandler handler) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), handler);
    }

/
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.acc = System.getSecurityManager() == null ?
                null :
                AccessController.getContext();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }
ScheduledThreadPoolExecutor
public class ScheduledThreadPoolExecutor
        extends ThreadPoolExecutor
        implements ScheduledExecutorService

继承了ThreadPoolExecutor,实现了ScheduledExecutorService中定时任务相关的方法。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5712342.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-18
下一篇 2022-12-18

发表评论

登录后才能评论

评论列表(0条)

保存