整整 Java 线程池

本文深入探讨了Java线程池的重要性,介绍了ExecutorService、ThreadPoolExecutor的构造方法和线程创建规则,以及ScheduledExecutorService与ForkJoinPool的特性。讨论了线程池的四种构造方法、线程池在不同任务量下的行为,以及Java提供的快捷线程池类型。通过理解这些,开发者可以更好地理解和使用Java线程池来提升性能和管理资源。
摘要由CSDN通过智能技术生成

整整 Java 线程池

用官方文档来说,线程池解决了两个问题: 一是在执行大量的异步任务时,因为线程池减少了任务开始前的准备工作,如频繁创建线程,启动线程等工作,提升了性能表现;二是提供了一种绑定资源和管理资源的途径,可以进行一些基础的统计分析,比如已经完成的任务数量等。

ExecutorService

接口,继承自 Executor,通过 execute 方法执行 Runnable 任务。ExecutorService 提供了管理终止异步任务的方法和通过 Future 对象追踪异步任务进度的方法。

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);
}

ExecutorService 可以被关闭,随后不再接受新的任务,资源可以被回收。通过 submit 方法扩展 execute 方法,返回一个 Future 对象用于取消执行或者等待执行完成。可以批量执行任务。

public interface ExecutorService extends Executor {

    /**
     * 已经提交的任务继续执行,不再接受新的任务
     */
    void shutdown();

    /**
     * 尝试停止正在执行的任务,没有执行的任务不再执行,不再接受新的任务
     * 返回没有执行的任务的列表
     */
    List<Runnable> shutdownNow();

    /**
     * 阻塞直到(所有任务完成(shutdown 后)| 超时 | 当前线程被中断)发生其一
     * 终止时返回 true,反之返回 false
     */
    boolean awaitTermination(long timeout, TimeUnit unit)
        throws InterruptedException;

    /**
     * 提交新任务,并返回一个 Future 对象用于获取执行结果信息
     */
    <T> Future<T> submit(Callable<T> task);
    <T> Future<T> submit(Runnable task, T result);
    Future<?> submit(Runnable task);

    /**
     * 执行给定的任务列表,返回任务结果信息的 Future 列表。可设定超时时间
     */
    <T> List<Future<T>> invokeAll(Collection<
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值