代码示例:

public class ThreadPool_Test {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService pool = Executors.newCachedThreadPool();
pool.execute(new MyRunner()); Future<String> future = pool.submit(new MyCaller());
String ret = future.get();
System.out.println(ret);
}
} class MyCaller implements Callable<String> { @Override
public String call() throws Exception {
System.out.println("calling");
return "return_from_call";
} } class MyRunner implements Runnable {
@Override
public void run() {
System.out.println("running");
} }

execute 方法执行 runnable 任务,submit 方法执行 callable 任务,callable 任务有返回值,而 runnable 任务是 void 的,无返回值。

// void java.util.concurrent.ThreadPoolExecutor
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) {
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) {
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);
}
}

对于 Runnable,task 是 MyRunner,对于 Callable,task 是 FutureTask。

submit 方法的调用栈:

创建 FutureTask 对象,把 Callable 对象包裹起来,在 run 方法中调用 Callable 对象的方法,并设置返回值。

// java.util.concurrent.FutureTask.FutureTask
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
} 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);
}
}

线程池 execute 和 submit 的区别的更多相关文章

  1. 详解线程池execute和submit用法

    在使用线程池时,我们都知道线程池有两种提交任务的方式,那么他们有什么区别呢? 1.execute提交的是Runnable类型的任务,而submit提交的是Callable或者Runnable类型的任务 ...

  2. 线程池提交任务的两种方式:execute与submit的区别

    Java中的线程池在进行任务提交时,有两种方式:execute和submit方法. 一.execute和submit的区别 execute只能提交Runnable类型的任务,无返回值.submit既可 ...

  3. execute和submit的区别与联系

    execute和submit都属于线程池的方法,execute只能提交Runnable类型的任务,而submit既能提交Runnable类型任务也能提交Callable类型任务. execute会直接 ...

  4. JAVA线程池shutdown和shutdownNow的区别

    一.区别介绍 shutDown()  当线程池调用该方法时,线程池的状态则立刻变成SHUTDOWN状态.此时,则不能再往线程池中添加任何任务,否则将会抛出RejectedExecutionExcept ...

  5. ThreadPoolExecutor中execute和submit的区别

    1:入参不同 excute() 传入的是 Runable, submit 传入的是 Callable 或 Runable 1):execute 方法源码 public void execute(Run ...

  6. ScheduledThreadPoolExecutor线程池scheduleAtFixedRate和scheduleWithFixedDelay的区别

    ScheduledFuture<?> result = executor.scheduleAtFixedRate(task,2, 5, TimeUnit.SECONDS); 在延迟2秒之后 ...

  7. Java 并发编程——Executor框架和线程池原理

    Eexecutor作为灵活且强大的异步执行框架,其支持多种不同类型的任务执行策略,提供了一种标准的方法将任务的提交过程和执行过程解耦开发,基于生产者-消费者模式,其提交任务的线程相当于生产者,执行任务 ...

  8. Java提高班(二)深入理解线程池ThreadPool

    本文你将获得以下信息: 线程池源码解读 线程池执行流程分析 带返回值的线程池实现 延迟线程池实现 为了方便读者理解,本文会由浅入深,先从线程池的使用开始再延伸到源码解读和源码分析等高级内容,读者可根据 ...

  9. 线程池-Executors

    合理使用线程池能够带来三个好处 减少创建和销毁线程上所花的时间以及系统资源的开销 提高响应速度.当任务到达时,任务可以不需要等到线程创建就能立即执行 提高线程的客观理性.线程是稀缺资源,如果无限制的创 ...

随机推荐

  1. 1. AMQP 0-9-1模型简介(官网直译)

    关于这篇指导文档 本文提供了AMQP 0-9-1协议的一个概述,它是RabbitMQ所支持的协议之一. AMQP 0-9-1是什么 AMQP 0-9-1(Advanced Message Queuin ...

  2. mutect/mutsig/gistic官网汇总

    http://software.broadinstitute.org/software/cprg/

  3. 一步到位之INNODB

    原文链接:http://imysql.com/2012/09/21/mysql-faq-setup-innodb-quickly.html 快速认识InnoDB InnoDB是MySQL下使用最广泛的 ...

  4. 《剑指offer》第五十五题(二叉树的深度)

    // 面试题55(一):二叉树的深度 // 题目:输入一棵二叉树的根结点,求该树的深度.从根结点到叶结点依次经过的 // 结点(含根.叶结点)形成树的一条路径,最长路径的长度为树的深度. //如果左右 ...

  5. d3 .each()

    d3.select("xxx") .each(function (d) { //this表示当前element 而 d表示绑定的数据 something(this); }); 注意 ...

  6. docker-compose在dockerfile更新后自动更新image

    比如在dockerfile里需要新安装包 形如 加一行 RUN pip3 install XXX 之后,希望docker-compose能更新镜像, 然后启动容器 只需要启动时使用 --build即可 ...

  7. P10.3 usestock0.cpp

    stock.h #ifndef STOCK_H #define STOCK_H #include <string> class Stock //类声明 { private: std::st ...

  8. vux的x-input的源码分析

    <template> <div class="vux-x-input weui-cell" :class="{'weui-cell_warn': sho ...

  9. win10如何一键开启关闭windows Defender(亲测有效)

    win10如何一键开启关闭windows Defender(亲测有效) 一.总结 一句话总结:各种找资料如何开启关闭都没用,直接下载软件简单方便 软件 因为我关windows defender是用的一 ...

  10. (转)C# 的 String.CompareTo、 Equals和==的比较

    String.CompareTo 语法 public int CompareTo(    string strB) 返回值 小于 0,实例小于参数 strB: 0,实例等于参数 strB: 大于 0, ...