ThreadPoolExecut线程池底层源码分析

ThreadPoolExecutor维护了一个负责执行任务的工作线程池。当任务被提交时,它会被添加到阻塞队列中。如果队列已满,ThreadPoolExecutor将创建一个新的工作线程,或者根据当前配置使用拒绝处理程序来处理任务。如果有空闲的工作线程可用,它们将用于执行任务。否则,将创建一个新的工作线程并将其添加到池中。每个工作线程都在一个无限循环中运行,从队列中提取任务并执行它们,直到没有任务剩余或线程中断。

public class ThreadPoolExecutor extends AbstractExecutorService {
    // internal queue to hold submitted tasks
    private final BlockingQueue<Runnable> workQueue;

    // set of worker threads that can be reused
    private final HashSet<Worker> workers = new HashSet<Worker>();

    // maximum number of worker threads to keep in the pool
    private int maximumPoolSize;

    // thread factory used to create new worker threads
    private ThreadFactory threadFactory;

    // rejection handler to use when the queue is full
    private RejectedExecutionHandler handler;

    public ThreadPoolExecutor(...) {
        workQueue = new LinkedBlockingQueue<Runnable>();
        // initialize other fields
    }

    // method to execute a task in the thread pool
    public void execute(Runnable task) {
        // try to add the task to the queue
        if (!workQueue.offer(task)) {
            // if the queue is full, try to create a new worker thread
            if (workers.size() < maximumPoolSize) {
                Worker worker = new Worker(task);
                workers.add(worker);
                worker.start();
            } else {
                // if the maximum number of threads is already reached,
                // use the rejection handler to handle the task
                handler.rejectedExecution(task, this);
            }
        }
    }

    // inner class representing a worker thread
    private final class Worker extends Thread {
        private Runnable task;

        public Worker(Runnable task) {
            this.task = task;
        }

        // run method for the worker thread
        public void run() {
            while (task != null || (task = workQueue.poll()) != null) {
                try {
                    task.run();
                } catch (RuntimeException e) {
                    // handle any exceptions that occur during task execution
                } finally {
                    task = null;
                }
            }

            // remove the worker thread from the set of active workers
            workers.remove(this);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值