Java 线程池框架

2019-01-22  本文已影响14人  自负的鱼

线程池通过多个任务重用线程方案,解决了线程的生命周期开销和资源不足的问题(不需要频繁创建和销毁线程)。

线程池优点:

java中的线程池使用ThreadPoolExecutor来实现,同时提供了Executor框架异步任务调度框架。

线程池的状态:

ThreadPoolExecutor 详解

java线程池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.acc = System.getSecurityManager() == null ?
                null :
                AccessController.getContext();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }

构造方法中的字段含义如下:

ThreadPoolExecutor提交任务

通过ThreadPoolExecutor的execute()方法用来提交任务,原理为通过addWorker()方法将任务封装为Worker线程对象。并执行Worker对象执行任务。

Worker对象为线程,实现了Runnable接口,Worker类中的run方法调用了runWorker方法来执行任务,该方法循环通过getTask()方法阻塞从workQueue队列中获取待执行的任务,调用任务的run()方法执行任务逻辑。

final void runWorker(Worker w) {
    Thread wt = Thread.currentThread();
    // 获取第一个任务
    Runnable task = w.firstTask;
    w.firstTask = null;
    // 允许中断
    w.unlock(); // allow interrupts
    // 是否因为异常退出循环
    boolean completedAbruptly = true;
    try {
        // 如果task为空,则通过getTask来获取任务
        while (task != null || (task = getTask()) != null) {
            w.lock();
            // If pool is stopping, ensure thread is interrupted;
            // if not, ensure thread is not interrupted.  This
            // requires a recheck in second case to deal with
            // shutdownNow race while clearing interrupt
            if ((runStateAtLeast(ctl.get(), STOP) ||
                 (Thread.interrupted() &&
                  runStateAtLeast(ctl.get(), STOP))) &&
                !wt.isInterrupted())
                wt.interrupt();
            try {
                beforeExecute(wt, task);
                Throwable thrown = null;
                try {
                    task.run();
                } catch (RuntimeException x) {
                    thrown = x; throw x;
                } catch (Error x) {
                    thrown = x; throw x;
                } catch (Throwable x) {
                    thrown = x; throw new Error(x);
                } finally {
                    afterExecute(task, thrown);
                }
            } finally {
                task = null;
                w.completedTasks++;
                w.unlock();
            }
        }
        completedAbruptly = false;
    } finally {
        processWorkerExit(w, completedAbruptly);
    }
}
上一篇 下一篇

猜你喜欢

热点阅读