JAVA线程池的一些见解

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.corePoolSize = corePoolSize;
    this.maximumPoolSize = maximumPoolSize;
    this.workQueue = workQueue;
    this.keepAliveTime = unit.toNanos(keepAliveTime);
    this.threadFactory = threadFactory;
    this.handler = handler;
}

corePoolSize:核心池的大小

maximumPoolSize:线程池最大线程数

keepAliveTime:表示线程没有任务执行时最多保持多久时间会终止

workQueue:一个阻塞队列,用来存储等待执行的任务

threadFactory:线程工厂,主要用来创建线程

handler:表示当拒绝处理任务时的策略

我关注的是2个地方

1:任务是如何管理的

2:线程池中的线程是如何管理,复用和超时机制如何生效

了解了这2个基本上线程池的主体就能知道了。

由上面可知workQueue是用来存储等待执行的任务,

1:任务是如何管理的
public void execute(Runnable command) {
    int c = ctl.get();
    if (workerCountOf(c) < corePoolSize) {//当前运行的线程是否小于核心线程数量
        if (addWorker(command, true))
            return;
        c = ctl.get();
    }
    if (isRunning(c) && workQueue.offer(command)) {//判断当前线程池是否处于运行状态,及将任务放入workQueue中
        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);
}:

2:那么线程是如何管理的呢?

在addWorker中线程被放入了work里面,然后放到works下面。

private boolean addWorker(Runnable firstTask, boolean core) {
...........................
    Worker w = null;
    try {
        w = new Worker(firstTask);
        final Thread t = w.thread;
        if (t != null) {
         ................................
                if (rs < SHUTDOWN ||
                    (rs == SHUTDOWN && firstTask == null)) {
                    if (t.isAlive()) // precheck that t is startable
                        throw new IllegalThreadStateException();
                    workers.add(w);
                    int s = workers.size();
                    if (s > largestPoolSize)
                        largestPoolSize = s;
                    workerAdded = true;
                }
            } finally {
                mainLock.unlock();
            }
            if (workerAdded) {
                t.start();
                workerStarted = true;
            ...........................
}

如果是新的线程池中没有空闲的线程,那么会新建一个线程并将该线程放到线程列表workers中。

HashSet<Worker> workers = new HashSet<>();

3:线程是如何复用?

t.start();后会调用work里面的run
public void run() {
    runWorker(this);
}
final void runWorker(Worker w) {
    Thread wt = Thread.currentThread();
    Runnable task = w.firstTask;
    w.firstTask = null;
    w.unlock(); // allow interrupts
    boolean completedAbruptly = true;
    try {
        while (task != null || (task = getTask()) != null) {//如果task不为空,那么运行当前的task,如果为空那么在getTask中从workQueue中获取 task 
            w.lock();
            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) {
                .......
                } finally {
                    afterExecute(task, thrown);
                }
            } finally {
                task = null;
                w.completedTasks++;
                w.unlock();
            }
        }
        completedAbruptly = false;
    } finally {
        processWorkerExit(w, completedAbruptly);
    }
}

如果task不为空,那么运行当前的task,如果为空那么在getTask中从workQueue中获取 task 。

如果当前有空闲的任务,那么新来的任务就会直接放入到workQueue中,然后work能获取到新的任务,新任务会在空闲的线程中直接运行了。线程池就是利用该方法复用线程的。

4:线程如何超时退出?

runWorker里面task = getTask() 从workQueue获取task。我们看看getTask做了是
private Runnable getTask() {
    boolean timedOut = false; // Did the last poll() time out?

    for (;;) {
     ............................

        boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
        try {
            Runnable r = timed ?
                workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
                workQueue.take();
            if (r != null)
                return r;
            timedOut = true;
        } catch (InterruptedException retry) {
            timedOut = false;
        }
    }
}

如果不是核心进程,那么会调用workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS)获取任务,keepAliveTime就是超时时间,如果超时了就会返回null,回到runWorker里面,如果 task为null,那么task != null || (task = getTask()) != null  就为false,那么就会直接跑到processWorkerExit里面,这个里面执行了线程的退出。

final void runWorker(Worker w) {
   .......................
    try {
        while (task != null || (task = getTask()) != null) {
        .....................
        }
        completedAbruptly = false;
    } finally {
        processWorkerExit(w, completedAbruptly);
    }
}
private void processWorkerExit(Worker w, boolean completedAbruptly) {
    ......................
    try {
        completedTaskCount += w.completedTasks;
        workers.remove(w);
    } finally {
        mainLock.unlock();
    }
    .......................
    }
}

在processWorkerExit中将w从works里面删除了,因为线程的run已经结束了,所以该线程一会被gc回收掉。

如果有问题请大家指出来,谢谢

猜你喜欢

转载自blog.csdn.net/dxh040431104/article/details/93365893