多线程之 线程池总结

JDK提供2种线程池,ThreadPoolExecutor、ForkJoinPool
这里先写ThreadPoolExecutor 有时间再写ForkJoinPool

ThreadPoolExecutor

JDK提供4种默认的线程池,实际上他们的底层都是ThreadPoolExecutor,通过传入构造方法的7个参数实现不同的功能

Executors.newSingleThreadExecutor(); // 单个线程的线程池
Executors.newCachedThreadPool(); // 0个核心线程
Executors.newFixedThreadPool(4); // 固定4个线程
Executors.newScheduledThreadPool(2); //

分别查看源码,分析7个参数,即可知其作用
前3个都比较简单,主要写下第四个
ScheduledThreadPool


public class ScheduledPoolTest {
   
    public static void main(String[] args) {
   
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(4);
        // 固定时间定时的去执行任务      参数分别是
        // 1.任务
        // 2.要延迟多久执行第一个任务
        // 3.任务执行推迟时间
        // 4.时间单位
        scheduledExecutorService.scheduleAtFixedRate(()->{
   
            
            System.out.println(Thread.currentThread().getName());
        },0,500, TimeUnit.MILLISECONDS);
    }
}

7个参数

 public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
   

查看4个默认线程池的源码,很容易知道他们的作用
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

从execute方法源码分析线程池执行任务过程

    public void execute(Runnable command) {
   
        if (command == null)
            throw new NullPointerException();
        /*
         * Proceed in 3 steps:
         *
         * 1. If fewer than corePoolSize threads are running, try to
         * start a new thread with the given command as its first
         * task.  The call to addWorker atomically checks runState and
         * workerCount, and so prevents false alarms that would add
         * threads when it shouldn't, by returning false.
         *
         * 2. If a task can be successfully queued, then we still need
         * to double-check whether we should have added a thread
         * (because existing ones died since last checking) or that
         * the pool shut down since entry into this method. So we
         * recheck state and if necessary roll back the enqueuing if
         * stopped, or start a new thread if there are none.
         *
         * 3. If we cannot 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值