mysterin / question_and_answer

1 stars 0 forks source link

线程池 shutdown 和 shutdownNow #101

Closed mysterin closed 5 years ago

mysterin commented 5 years ago

shutdown

public void shutdown() {
    final ReentrantLock mainLock = this.mainLock;
    mainLock.lock();
    try {
        checkShutdownAccess();
        advanceRunState(SHUTDOWN);
        interruptIdleWorkers();
        onShutdown(); // hook for ScheduledThreadPoolExecutor
    } finally {
        mainLock.unlock();
    }
    tryTerminate();
}

不再接收新任务, 同时把空闲的线程中断, 最后会等任务队列的任务都执行完才算关闭线程池. 至于如何判断线程是否空闲, 它会使用 tryLock() 方法尝试获取锁, 可以成功说明线程是空闲的, 不然就说明线程正在执行任务, 跳过不中断.

shutdownNow

public List<Runnable> shutdownNow() {
    List<Runnable> tasks;
    final ReentrantLock mainLock = this.mainLock;
    mainLock.lock();
    try {
        checkShutdownAccess();
        advanceRunState(STOP);
        interruptWorkers();
        tasks = drainQueue();
    } finally {
        mainLock.unlock();
    }
    tryTerminate();
    return tasks;
}

不再接收新任务, 同时会对所有线程做中断处理, 不管是否还在执行任务, 最后会返回为执行的任务列表.