线程池 execute 和 submit 的区别
代码示例:
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 的区别的更多相关文章
- 详解线程池execute和submit用法
在使用线程池时,我们都知道线程池有两种提交任务的方式,那么他们有什么区别呢? 1.execute提交的是Runnable类型的任务,而submit提交的是Callable或者Runnable类型的任务 ...
- 线程池提交任务的两种方式:execute与submit的区别
Java中的线程池在进行任务提交时,有两种方式:execute和submit方法. 一.execute和submit的区别 execute只能提交Runnable类型的任务,无返回值.submit既可 ...
- execute和submit的区别与联系
execute和submit都属于线程池的方法,execute只能提交Runnable类型的任务,而submit既能提交Runnable类型任务也能提交Callable类型任务. execute会直接 ...
- JAVA线程池shutdown和shutdownNow的区别
一.区别介绍 shutDown() 当线程池调用该方法时,线程池的状态则立刻变成SHUTDOWN状态.此时,则不能再往线程池中添加任何任务,否则将会抛出RejectedExecutionExcept ...
- ThreadPoolExecutor中execute和submit的区别
1:入参不同 excute() 传入的是 Runable, submit 传入的是 Callable 或 Runable 1):execute 方法源码 public void execute(Run ...
- ScheduledThreadPoolExecutor线程池scheduleAtFixedRate和scheduleWithFixedDelay的区别
ScheduledFuture<?> result = executor.scheduleAtFixedRate(task,2, 5, TimeUnit.SECONDS); 在延迟2秒之后 ...
- Java 并发编程——Executor框架和线程池原理
Eexecutor作为灵活且强大的异步执行框架,其支持多种不同类型的任务执行策略,提供了一种标准的方法将任务的提交过程和执行过程解耦开发,基于生产者-消费者模式,其提交任务的线程相当于生产者,执行任务 ...
- Java提高班(二)深入理解线程池ThreadPool
本文你将获得以下信息: 线程池源码解读 线程池执行流程分析 带返回值的线程池实现 延迟线程池实现 为了方便读者理解,本文会由浅入深,先从线程池的使用开始再延伸到源码解读和源码分析等高级内容,读者可根据 ...
- 线程池-Executors
合理使用线程池能够带来三个好处 减少创建和销毁线程上所花的时间以及系统资源的开销 提高响应速度.当任务到达时,任务可以不需要等到线程创建就能立即执行 提高线程的客观理性.线程是稀缺资源,如果无限制的创 ...
随机推荐
- json扩展
using Newtonsoft.Json.Linq; namespace Utility { public static class JsonExt { /// <summary> // ...
- Android Studio 使用USB真机调试教程
允许安装未知来源的软件 允许USB调试 设置启动方式 选择USB device 然后运行 会自动安装软件启动! 参考: https://blog.csdn.net/fubo1990/article/d ...
- JS中UTF-8和UTF-16互转
1.由于服务端使用的Go,默认是使用UTF-8编码的,而JS默认是Unicode编码的(也就是UTF-16),所以为了字符串编码的一致性,将前端字符串数据编码转换为UTF-8之后再发送给服务端,服务端 ...
- 关于select的默认样式问题
select { border: solid 1px #000; appearance:none; -moz-appearance:none; -webkit-appearance:none; pad ...
- Asp.net core 学习笔记 (Excel 读写)
EPPlus 已经支持 .net core 了 https://www.nuget.org/packages/EPPlus https://github.com/JanKallman/EPPlus 写 ...
- Java定时器的三种实现方式
一.普通thread /** * 普通thread * 这是最常见的,创建一个thread,然后让它在while循环里一直运行着, * 通过sleep方法来达到定时任务的效果.这样可以快速简单的实现, ...
- office2016如何激活
office2016如何激活 一.总结 一句话总结:office2016没有激活成功,下了一个office2013破解版 office2013破解版 二.自己做法 三中的方法点赞蛮多的(100多个), ...
- 雷林鹏分享:服务器上的 XML
服务器上的 XML XML 文件是类似 HTML 文件的纯文本文件. XML 能够通过标准的 Web 服务器轻松地存储和生成. 在服务器上存储 XML 文件 XML 文件在 Internet 服务器上 ...
- Mycat水平拆分之十种分片规则
水平切分分片实现 配置schema.xml 在同一个mysql数据库中,创建了三个数据库 testdb1,testdb2,testdb3.并在每个库中都创建了user表 <?xml ...
- 树分治TLE原因
1.树分治有logn层,如果各层都进行一次memset相当于大小没变,可能TLE: 2.根节点全局变量会变,需要用局部变量记录,还有子树大小. 3.找根的时候的size是当前size,而不是输入数据中 ...