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

三连哦

一、线程回顾

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 参数说明

* @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、开发中为什么使用线程池

  • 降低资源的消耗

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

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

    • 线程池会根据当前系统特点对池内的线程进行优化处理,减少创建和销毁线程带来的系统开销。无限的创建和销毁线程不仅消耗系统资源,还降低系统的稳定性,使用线程池进行统一分配

猜你喜欢

转载自blog.csdn.net/weixin_43304253/article/details/129978907