Executor的线程池

本文深入解析Java中四种常见线程池的实现原理与应用场景,包括newSingleThreadExecutor、newFixedThreadPool、newCachedThreadPool和newScheduledThreadPool。通过源码分析,揭示线程池如何高效管理线程,以及在不同场景下选择合适线程池的策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

newSingleThreadExecutor

	public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }
    // FinalizableDelegatedExecutorService 如下:
     static class FinalizableDelegatedExecutorService
        extends DelegatedExecutorService {
        FinalizableDelegatedExecutorService(ExecutorService executor) {
            super(executor);
        }
        protected void finalize() {
            super.shutdown();
        }
    }
	继续回到顶端,研究 ThreadPoolExecutor。
   // 处理任务部分
 	public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
        int c = ctl.get();
        // 如果工作的任务数 小于  核心线程池数,直接新启动一个线程
        if (workerCountOf(c) < corePoolSize) {
            if (addWorker(command, true))
                return;
            c = ctl.get();
        }
        // 如果工作的任务数 大于核心线程池数,可以入缓冲队列
        if (isRunning(c) && workQueue.offer(command)) {
            int recheck = ctl.get();
            if (! isRunning(recheck) && remove(command))
                reject(command);
            else if (workerCountOf(recheck) == 0)
                addWorker(null, false);
        }
        // 如果缓冲队列也满了,新启动一个线程。当前工作 的线程数达到最大线程数的时候,开始拒绝服务。
        else if (!addWorker(command, false))
            reject(command);
    }
    然后再看 newSingleThreadExecutor 就很清晰了,
    corePoolSize  设置了 1
    maximumPoolSize 设置了 1
    所以它从头到尾就一个线程在工作。

newFixedThreadPool:

	 public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }
	这个和上面的 newSingleThreadPool 差不多,不过是把1个改成了 N个
newCachedThreadPool:
	public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }
    如果线程池的大小超过了处理任务所需要的线程,那么就会回收部分空闲(60秒不执行任务)的线程,当任务数增加时,此线程池又可以智能的添加新线程来处理任务。此线程池不会对线程池大小做限制,线程池大小完全依赖于操作系统(或者说JVM)能够创建的最大线程大小。
    

newScheduledThreadPool:

     public ScheduledThreadPoolExecutor(int corePoolSize) {
        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
              new DelayedWorkQueue());
    }
   创建一个支持定时操作的线程池。看一下执行方法。
    public void execute(Runnable command) {
        schedule(command, 0, NANOSECONDS);
    }
    //  可以直接调用此方法进行定时设置
    public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
        if (command == null || unit == null)
            throw new NullPointerException();
        RunnableScheduledFuture<?> t = decorateTask(command,
            new ScheduledFutureTask<Void>(command, null,
                                          triggerTime(delay, unit)));
        delayedExecute(t);   // 处理任务操作
        return t;
    }
    private void delayedExecute(RunnableScheduledFuture<?> task) {
        if (isShutdown())
            reject(task);
        else {
            super.getQueue().add(task);
            if (isShutdown() &&
                !canRunInCurrentRunState(task.isPeriodic()) &&
                remove(task))
                task.cancel(false);
            else
                ensurePrestart();
        }
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值