execute与submit

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/weixin_43213517/article/details/96013415
Execute与Submit

These two methods are the method to call when submitting tasks to the thread pool, then the two methods in the end what difference does it make?

Thread Pool execute source code analysis method
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);
}
  • First parameter is determined as a null null pointer exception is thrown.
  • Current number of threads to determine whether the core is smaller than the number of threads? If the method is to call addWorker.
  • The current number of threads is greater than the core number of threads: the current task and then placed in the blocking queue.
  • Core and queues are full, to create a non-core thread to perform, if the full implementation of refusal strategies.
Thread Pool submit source code analysis method
public Future<?> submit(Runnable task) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<Void> ftask = newTaskFor(task, null);
        execute(ftask);
        return ftask;
    }

Essentially execute method is called, but it will be passed in the Runnable task to do a package, so that this becomes a target RunnableFuture method can return a Future object, by finally get method Future class can be obtained return value.

Guess you like

Origin blog.csdn.net/weixin_43213517/article/details/96013415