JAVAEE之线程(10)_线程池、线程池的创建、实现线程池

一 线程池

1.1为什么要有线程池?

 线程池顾名思义是由多个线程所组成,作用就是减少线程的建立与销毁,与数据库连接池相同概念,为了减少连接与释放,从而降低消耗提升效率。

1.2 线程池的优势

总体来说,线程池有如下的优势:

  1. 降低资源消耗。通过重复利用已创建的线程降低线程创建和销毁造成的消耗。

  2. 提高响应速度。当任务到达时,任务可以不需要等到线程创建就能立即执行。

  3. 提高线程的可管理性。线程是稀缺资源,如果无限制的创建,不仅会消耗系统资源,还会降低系统的稳定性,使用线程池可以进行统一的分配,调优和监控。

1.3 线程池的创建

 在JAVA的标准库中,通过Executor框架的工具类Executors来创建线程池。Executors 创建线程池的几种方式:

  1. newFixedThreadPool: 创建固定线程数的线程池;
  2. newCachedThreadPool: 创建线程数目动态增长的线程池;
  3. newSingleThreadExecutor: 创建只包含单个线程的线程池;
  4. newScheduledThreadPool: 设定 延迟时间后执行命令,或者定期执行命令。
package PoolThread;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Zhang
 * @date 2024/5/1119:48
 * @Description:
 */
public class Test {

    public static void main(String[] args) {
        ExecutorService service  = Executors.newCachedThreadPool();   //此时构造出的线程池对象,有一个基本的特点:线程数目是能够自适应的
        ExecutorService service1 = Executors.newFixedThreadPool(4);  //创造线程的数目是固定的
        ExecutorService service2 = Executors.newSingleThreadExecutor();   //只有一个线程的线程池
        ExecutorService service3 = Executors.newScheduledThreadPool(500);   //设定 延迟时间后执行命令,或者定期执行命令
        
        service1.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println("Hello World");
            }
        });
    }
}

注意:Executors 本质上是 ThreadPoolExecutor 类的封装。ThreadPoolExecutor 提供了更多的可选参数, 可以进一步细化线程池行为的设定,我们将后续介绍
在这里插入图片描述

二、 通过ThreadPoolExecutor创建线程池

2.1 其构造方法有如下4种

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

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

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

我们主要看第四个方法,因为其他几个构造方法都是调用这个。

//4. 
    /**
     * 用给定的初始参数创建一个新的ThreadPoolExecutor。
     */
    public ThreadPoolExecutor(int corePoolSize,//线程池的核心线程数量
                              int maximumPoolSize,//线程池的最大线程数
                              long keepAliveTime,//当线程数大于核心线程数时,多余的空闲线程存活的最长时间
                              TimeUnit unit,//时间单位
                              BlockingQueue<Runnable> 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.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }


ThreadPoolExecutor中的参数说明:

  1. corePoolSize:核心线程数maximumPoolSize:最大线程数,任务队列存放的任务达到队列容量的时候,同时运行的最大线程数量。
  2. workQueue:新的任务进来的时候,先判断当前运行的线程数是否大于或者核心线程数,如果达到,则会被放入队列中。
  3. keepAliveTime:线程池中的线程数量>核心线程数,如果这时未有新任务提交,非核心线程不会立即销毁,而是会等待,直到等待时间超过了keepAliveTime才会被回收。
  4. unit:keepAliveTime 参数的时间单位。
  5. threadFactory:线程工厂 用来创建线程,一般默认即可。
  6. handler:拒绝策略,如果当前的线程数已经达到最大线程数,并且队列中也被放满了任务,则需要执行拒绝策略。
    ThreadPoolExecutor.AbortPlicy:抛出异常,默认策略。ThreadPoolExecutor.DiscardPolicy:直接丢弃任务,但不抛出异常。
    ThreadPoolExecutor.DsicardOldestPolicy:丢弃最早的任务,将新任务加入队列。
    ThreadPoolExecutor.CallerRunsPolicy:由线程池所在的的线程处理任务,自己处理自己的。

2.2 使用ThreadPoolExecutor正确创建线程池

static ThreadFactory factory = new ThreadFactoryBuilder().setNameFormat("创建线程").build();

  static ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 20, 60, TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(30), factory, new ThreadPoolExecutor.AbortPolicy());

    public static class MyThread implements Runnable {
        @Override
        public void run() {
            System.out.println("创建线程成功");
        }
    }
    public static void main(String[] args){
        MyThread myThread = new MyThread();
        executor.submit(myThread);
    }

其中,调用线程执行有两个方法,submit和execute:

  1. submit的作用是可以通过return获取返回值;
  2. execute是无返回值的。

三、自己实现一个线程

实现过程:

  1. 核心操作为 submit, 将任务加入线程池中;
  2. 使用 Worker 类描述一个工作线,使用 Runnable 描述一个任务;
  3. 使用一个 BlockingQueue 组织所有的任务;
  4. 每个 worker 线程要做的事情: 不停的从 BlockingQueue 中取任务并执行;
  5. 指定一下线程池中的最大线程数 maxWorkerCount; 当当前线程数超过这个最大值时, 就不再新增线程了。

相关实例实现代码:

package PoolThread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingDeque;

/**
 * @author Zhang
 * @date 2024/5/1120:28
 * @Description:
 */


class  MyThreadPool{
    //任务队列
    private ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(1000);

    //通过这个方法,把任务添加到队列中
    public void submit(Runnable runnable) throws InterruptedException {

        //阻塞等待
        queue.put(runnable);
    }


    public  MyThreadPool(int n){
        //创建n个线程,负责执行上述队列的任务
        for (int i = 0; i < n; i++) {
            Thread t = new Thread(()->{
                try {
                    //让这个线程,从队列中消除任,并进行执行
                    Runnable runnable =  queue.take();
                    runnable.run();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            });
            t.start();
        }
    }

}
public class Test2 {

    public static void main(String[] args) throws InterruptedException {

        MyThreadPool myThreadPool = new MyThreadPool(4);
        for (int i = 0; i < 1000; i++) {
            int id = i;
            myThreadPool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("执行任务"+ id);
                }
            });
        }

    }
}

  • 25
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值