异步&线程池 线程池的七大参数 初始化线程的4种方式 【上篇】

简介: 这篇文章详细介绍了Java中线程的四种初始化方式,包括继承Thread类、实现Runnable接口、实现Callable接口与FutureTask结合使用,以及使用线程池。同时,还深入探讨了线程池的七大参数及其作用,解释了线程池的运行流程,并列举了四种常见的线程池类型。最后,阐述了在开发中使用线程池的原因,如降低资源消耗、提高响应速度和增强线程的可管理性。

一、线程回顾

1、初始化线程的 4 种方式

1)、继承 Thread
2)、实现 Runnable 接口
3)、实现 Callable 接口 + FutureTask (可以拿到返回结果,可以处理异常)
4)、线程池

提示

  • 方式 1 和方式 2:主进程无法获取线程的运算结果。不适合当前场景
  • 方式 3:主进程可以获取线程的运算结果,但是不利于控制服务器中的线程资源。可以导致服务器资源耗尽。
  • 方式 4:通过如下两种方式初始化线程池
Executors.newFiexedThreadPool(3);
//或者
new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit unit, workQueue, threadFactory, handler);

通过线程池性能稳定,也可以获取执行结果,并捕获异常。但是,在业务复杂情况下,一个异步调用可能会依赖于另一个异步调用的执行结果

1.1 继承 Thread

public class ThreadTestDemo {
    public static void main(String[] args) {
        System.out.println("main.....start......");
        Thread01 thread01 = new Thread01();
        thread01.start(); //启动线程
        System.out.println("main.....end......");

    }

    public static class Thread01 extends Thread{
        @Override
        public void run() {
            System.out.println("当前线程是:"+Thread.currentThread().getId());
            int i = 8 / 2;
            System.out.println("运算结果是:"+i);
        }
    }
}

结果

在这里插入图片描述


1.2 实现 Runnable 接口

public class ThreadTestDemo {
    public static void main(String[] args) {
        System.out.println("main.....start......");
        Runnable01 runnable01 = new Runnable01();
        new Thread(runnable01).start();
        System.out.println("main.....end......");

    }

    /**
     * 实现 Runnable 接口
     */
    public static class Runnable01 implements Runnable{
        @Override
        public void run() {
            System.out.println("当前线程是:"+Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运算结果是:"+i);
        }
    }
}

在这里插入图片描述

1.3 实现 Callable 接口

public class ThreadTestDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("main.....start......");
        FutureTask<Integer> futureTask = new FutureTask<>(new Callable01());
        new Thread(futureTask).start();
        //阻塞等待整个线程执行完成,获取返回结果
        Integer integer = futureTask.get();
        System.out.println("获取到的线程返回结果是:"+integer);
        System.out.println("main.....end......");

    }

    /**
     * 实现 Callable 接口 + FutureTask (可以拿到返回结果,可以处理异常)
     */
    public static class Callable01 implements Callable<Integer>{
        @Override
        public Integer call() throws Exception {
            System.out.println("当前线程是:"+Thread.currentThread().getId());
            int i = 12 / 2;
            System.out.println("运算结果是:"+i);
            return i;
        }
    }
}

测试结果

在这里插入图片描述

1.4 线程池

public class ThreadTestDemo {
    public static ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("main.....start......");
        //提交给线程池去执行
        executor.execute(new Runnable01());
        System.out.println("main.....end......");

    }

    /**
     * 实现 Runnable 接口
     */
    public static class Runnable01 implements Runnable{
        @Override
        public void run() {
            System.out.println("当前线程是:"+Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运算结果是:"+i);
        }
    }

}

执行结果

在这里插入图片描述

2、线程池的七大参数

2.1 参数说明

  • corePoolSize:核心线程数量 一直正在保持运行的线程
  • maximumPoolSize:最大线程数,线程池允许创建的最大线程数。
  • keepAliveTime:超出 corePoolSize 后创建的线程的存活时间。
  • unit:keepAliveTime 的时间单位。
  • workQueue:任务队列,用于保存待执行的任务。
  • threadFactory:线程池内部创建线程所用的工厂。
  • handler:任务无法执行时的处理器。
* @param corePoolSize the number of threads to keep in the pool, even
* if they are idle, unless {@code allowCoreThreadTimeOut} is set
池中一直保持的线程的数量,即使线程空闲。除非设置了 allowCoreThreadTimeOut
* @param maximumPoolSize the maximum number of threads to allow in the
* pool
池中允许的最大的线程数
* @param keepAliveTime when the number of threads is greater than
* the core, this is the maximum time that excess idle threads
* will wait for new tasks before terminating. 当线程数大于核心线程数的时候,线程在最大多长时间没有接到新任务就会终止释放,
最终线程池维持在 corePoolSize 大小
* @param unit the time unit for the {@code keepAliveTime} argument
时间单位
* @param workQueue the queue to use for holding tasks before they are
* executed. This queue will hold only the {@code Runnable}
* tasks submitted by the {@code execute} method. 阻塞队列,用来存储等待执行的任务,如果当前对线程的需求超过了 corePoolSize
大小,就会放在这里等待空闲线程执行。
* @param threadFactory the factory to use when the executor
* creates a new thread
创建线程的工厂,比如指定线程名等
* @param handler the handler to use when execution is blocked
* because the thread bounds and queue capacities are reached
拒绝策略,如果线程满了,线程池就会使用拒绝策略。

在这里插入图片描述

2.2 运行流程

  • 1、线程池创建,准备好 core 数量的核心线程,准备接受任务
  • 2、新的任务进来,用 core 准备好的空闲线程执行。
    • (1) 、core 满了,就将再进来的任务放入阻塞队列中。空闲的 core 就会自己去阻塞队列获取任务执行
    • (2) 、阻塞队列满了,就直接开新线程执行,最大只能开到 max 指定的数量
    • (3) 、max 都执行好了。Max-core 数量空闲的线程会在 keepAliveTime 指定的时间后自动销毁。最终保持到 core 大小
    • (4) 、如果线程数开到了 max 的数量,还有新任务进来,就会使用 reject 指定的拒绝策略进行处理
  • 3、所有的线程创建都是由指定的 factory 创建的。

3、常见的 4 种线程池

  • newCachedThreadPool

    • 创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
  • newFixedThreadPool

    • 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
  • newScheduledThreadPool

    • 创建一个定长线程池,支持定时及周期性任务执行。
  • newSingleThreadExecutor

    • 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。

在这里插入图片描述


3.1 newCachedThreadPool

在这里插入图片描述

3.2 newFixedThreadPool

在这里插入图片描述

3.3 newScheduledThreadPool

在这里插入图片描述

3.4 newSingleThreadExecutor

在这里插入图片描述

4、开发中为什么使用线程池

  • 降低资源的消耗

    • 通过重复利用已经创建好的线程降低线程的创建和销毁带来的损耗
  • 提高响应速度

    • 因为线程池中的线程数没有超过线程池的最大上限时,有的线程处于等待分配任务的状态,当任务来时无需创建新的线程就能执行
  • 提高线程的可管理性

    • 线程池会根据当前系统特点对池内的线程进行优化处理,减少创建和销毁线程带来的系统开销。无限的创建和销毁线程不仅消耗系统资源,还降低系统的稳定性,使用线程池进行统一分配
相关文章
|
4月前
|
缓存 Java
线程池的核心参数
线程池七大参数解析:核心线程数决定常驻线程,最大线程数控制并发上限,存活时间管理非核心线程生命周期,工作队列缓存待处理任务,线程工厂定制线程属性,拒绝策略应对任务过载,提升系统稳定性与资源利用率。
329 1
|
5月前
|
数据采集 存储 JSON
Python爬取知乎评论:多线程与异步爬虫的性能优化
Python爬取知乎评论:多线程与异步爬虫的性能优化
|
2月前
|
设计模式 缓存 安全
【JUC】(6)带你了解共享模型之 享元和不可变 模型并初步带你了解并发工具 线程池Pool,文章内还有饥饿问题、设计模式之工作线程的解决于实现
JUC专栏第六篇,本文带你了解两个共享模型:享元和不可变 模型,并初步带你了解并发工具 线程池Pool,文章中还有解决饥饿问题、设计模式之工作线程的实现
177 2
|
Java 存储
线程池的核心参数有哪些?
线程池七大核心参数:核心/最大线程数、线程保持时间及单位、阻塞队列、线程工厂与拒绝策略。
772 79
|
9月前
|
缓存 Java
线程池初始化严禁使用Executors
线程池初始化严禁使用Executors
|
5月前
|
数据采集 监控 调度
干货分享“用 多线程 爬取数据”:单线程 + 协程的效率反超 3 倍,这才是 Python 异步的正确打开方式
在 Python 爬虫中,多线程因 GIL 和切换开销效率低下,而协程通过用户态调度实现高并发,大幅提升爬取效率。本文详解协程原理、实战对比多线程性能,并提供最佳实践,助你掌握异步爬虫核心技术。
|
8月前
|
Java
线程池是什么?线程池在实际工作中的应用
总的来说,线程池是一种有效的多线程处理方式,它可以提高系统的性能和稳定性。在实际工作中,我们需要根据任务的特性和系统的硬件能力来合理设置线程池的大小,以达到最佳的效果。
244 18
|
9月前
|
Java
线程池的核心参数有哪些 ?
corePoolSize 核心线程数量 maximumPoolSize 最大线程数量 keepAliveTime 线程保持时间,N个时间单位 unit 时间单位(比如秒,分) workQueue 阻塞队列 threadFactory 线程工厂 handler 线程池拒绝策略
|
2月前
|
Java
如何在Java中进行多线程编程
Java多线程编程常用方式包括:继承Thread类、实现Runnable接口、Callable接口(可返回结果)及使用线程池。推荐线程池以提升性能,避免频繁创建线程。结合同步与通信机制,可有效管理并发任务。
161 6
|
5月前
|
Java API 微服务
为什么虚拟线程将改变Java并发编程?
为什么虚拟线程将改变Java并发编程?
306 83

热门文章

最新文章