简单解析execute和submit有什么区别

 更新时间:2020年11月10日 10:25:25   作者:牛鼻子老赵  
这篇文章主要介绍了简单解析execute和submit有什么区别,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

1、execute 方法位于 java.util.concurrent.Executor 中

void execute(Runnable command);

2、execute 的具体实现

public void execute(Runnable command) {
    if (command == null)
      throw new NullPointerException();
    /*
     * Proceed in 3 steps:
     *
     * 1. If fewer than corePoolSize threads are running, try to
     * start a new thread with the given command as its first
     * task. The call to addWorker atomically checks runState and
     * workerCount, and so prevents false alarms that would add
     * threads when it shouldn't, by returning false.
     *
     * 2. If a task can be successfully queued, then we still need
     * to double-check whether we should have added a thread
     * (because existing ones died since last checking) or that
     * the pool shut down since entry into this method. So we
     * recheck state and if necessary roll back the enqueuing if
     * stopped, or start a new thread if there are none.
     *
     * 3. If we cannot queue task, then we try to add a new
     * thread. If it fails, we know we are shut down or saturated
     * and so reject the task.
     */
    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);
  }

3、submit 方法位于 java.util.concurrent.AbstractExecutorService 中

/**
   * @throws RejectedExecutionException {@inheritDoc}
   * @throws NullPointerException    {@inheritDoc}
   */
  public Future<?> submit(Runnable task) {
    if (task == null) throw new NullPointerException();
    RunnableFuture<Void> ftask = newTaskFor(task, null);
    execute(ftask);
    return ftask;
  }

  /**
   * @throws RejectedExecutionException {@inheritDoc}
   * @throws NullPointerException    {@inheritDoc}
   */
  public <T> Future<T> submit(Runnable task, T result) {
    if (task == null) throw new NullPointerException();
    RunnableFuture<T> ftask = newTaskFor(task, result);
    execute(ftask);
    return ftask;
  }

  /**
   * @throws RejectedExecutionException {@inheritDoc}
   * @throws NullPointerException    {@inheritDoc}
   */
  public <T> Future<T> submit(Callable<T> task) {
    if (task == null) throw new NullPointerException();
    RunnableFuture<T> ftask = newTaskFor(task);
    execute(ftask);
    return ftask;
  }

4、submit 方式使用 Runnable 入参时的具体实现

static final class RunnableAdapter<T> implements Callable<T> {
    final Runnable task;
    final T result;
    RunnableAdapter(Runnable task, T result) {
      this.task = task;
      this.result = result;
    }
    public T call() {
      task.run();
      return result;
    }
  }

5、submit 方式使用 Callable 入参时的具体实现

public FutureTask(Callable<V> callable) {
    if (callable == null)
      throw new NullPointerException();
    this.callable = callable;
    this.state = NEW;    // ensure visibility of callable
  }

  //重写run方法
  public void run() {
    if (state != NEW ||
      !UNSAFE.compareAndSwapObject(this, runnerOffset,
                     null, Thread.currentThread()))
      return;
    try {
      Callable<V> c = callable;
      if (c != null && state == NEW) {
        V result;
        boolean ran;
        try {
          result = c.call();
          ran = true;
        } catch (Throwable ex) {
          result = null;
          ran = false;
          setException(ex);
        }
        if (ran)
          set(result);
      }
    } finally {
      // runner must be non-null until state is settled to
      // prevent concurrent calls to run()
      runner = null;
      // state must be re-read after nulling runner to prevent
      // leaked interrupts
      int s = state;
      if (s >= INTERRUPTING)
        handlePossibleCancellationInterrupt(s);
    }
  }

总结:

1、根据源码可以看到 execute 仅可以接受Runnable类型,而 submit 重载了三个方法,参数可以是 Runnable 类型、Runnable 类型+泛型T 、Callable 类型接口。

2、从上面源码可以看出 submit 方法实际上如果用Runnable类型的接口可以有返回值,也可以没有返回值。

3、传递Runnable类型接口加泛型T会被进一步封装,在 Executors 这个类里面有个内部类 RunnableAdapter 实现了 Callable 接口。

4、看submit方法可以看出,submit最终也是在调用 execute 方法,无论是 Runnable 还是 Callable 类型接口,都会被封装成 FutureTask 继续执行。

5、如果使用submit方法提交,会进一步封装成FutureTask,执行execute方法,在FutureTask里面重写的run方法里面调用 Callable 接口的call方法。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • 使用SpringBoot跨系统调用接口的方案

    使用SpringBoot跨系统调用接口的方案

    这篇文章主要介绍了使用SpringBoot跨系统调用接口的方案,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-01-01
  • Spring中的AutowireCandidateResolver的具体使用详解

    Spring中的AutowireCandidateResolver的具体使用详解

    这篇文章主要介绍了Spring中的AutowireCandidateResolver的具体使用详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-04-04
  • java实现简单验证码生成

    java实现简单验证码生成

    这篇文章主要介绍了java实现简单验证码生成,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-10-10
  • SpringSecurity之SecurityContextHolder使用解读

    SpringSecurity之SecurityContextHolder使用解读

    这篇文章主要介绍了SpringSecurity之SecurityContextHolder使用解读,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-03-03
  • mybatis中xml之trim属性说明

    mybatis中xml之trim属性说明

    这篇文章主要介绍了mybatis中xml之trim属性说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-07-07
  • Java根据日期截取字符串的多种实现方法

    Java根据日期截取字符串的多种实现方法

    在实际开发中,我们经常会遇到需要根据日期来截取字符串的需求,例如从文件名中提取日期信息,Java 提供了多种方法来实现根据日期来截取字符串的功能,本文将给大家介绍了Java根据日期截取字符串的多种实现方法,需要的朋友可以参考下
    2024-11-11
  • 详解Java如何简化条件表达式

    详解Java如何简化条件表达式

    在复杂的实际业务中,往往会出现各种嵌套的条件判断逻辑。随着需求的增加,条件逻辑会变得越来越复杂。面对这种情况,简化判断逻辑就是不得不做的事情,下面为大家介绍几种方法
    2022-06-06
  • idea切换分支的时候,忽略一些无用的修改设置

    idea切换分支的时候,忽略一些无用的修改设置

    这篇文章主要介绍了idea切换分支的时候,忽略一些无用的修改操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-02-02
  • 如何在mapper文件中使用in("str1","str2")

    如何在mapper文件中使用in("str1","str2")

    这篇文章主要介绍了如何在mapper文件中使用in("str1","str2"),具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-01-01
  • idea如何debug看springsecurity的过滤器顺序

    idea如何debug看springsecurity的过滤器顺序

    这篇文章主要介绍了idea如何debug看springsecurity的过滤器顺序,文中通过图文结合的方式给大家介绍的非常详细,对大家的学习或工作有一定的帮助,需要的朋友可以参考下
    2024-04-04

最新评论