线程池 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
合理使用线程池能够带来三个好处 减少创建和销毁线程上所花的时间以及系统资源的开销 提高响应速度.当任务到达时,任务可以不需要等到线程创建就能立即执行 提高线程的客观理性.线程是稀缺资源,如果无限制的创 ...
随机推荐
- MyBatis数据库测试代码自动生成
<!-- generatorConfig.xml配置,其中:<plugin type="org.mybatis.generator.plugins.ToStringPlugin& ...
- [从零开始搭网站六]为域名申请免费SSL证书(https),并为Tomcat配置https域名所用的多SSL证书
点击下面连接查看从零开始搭网站全系列 从零开始搭网站 由于国内的网络环境比较恶劣,运营商流量劫持的情况比较严重,一般表现为别人打开你的网站的时候会弹一些莫名其妙的广告...更过分的会跳转至别的网站. ...
- Intellij idea注册码失效
从网上下载idea需要输入激活码,晚上用的激活码大多是同一个,但是上次使用的时候突然弹窗告诉我注册码失效了,在网上找到一个新的方法 在注册界面有几个选项,我们常用的是Activation Code,现 ...
- 3.git、TortoiseGit的安装、仓库的配置教程
参考:https://blog.csdn.net/hc_ttxs/article/details/79375788 引言: Git: 就是最原始的分布式版本控制系统,是开源的. GitHub:与Git ...
- ORA-00604的解决方法
分类: Oracle 从错误的角度可以推出:应该是表空间不足 根据查看表空间的使用情况: select b.file_name 物理文件名, b.tablespace_name 表空间, b.by ...
- html5 history 信息api pushState
这个功能可以进行传参,还可以解决ajax无法前进和倒退的问题 首先,history新增的两个方法history.replaceState()和history.pushState()方法属于HTML5浏 ...
- 如何模拟一个http请求并把response的内容保存下载下来,导出到excel中(结尾福利)
def doExport(self): # 模拟一个http请求 url = u'%s?dumptype=investigation&dumpid=%s&timezone=8' % ( ...
- CRC分段校验
crc16 modbus分段校验码: const uint8_t ModbusCRCHighTab[] = { 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x ...
- C语言转义字符基础总结
C语言转义字符总结 C语言中的转义字符,是字符常量中很特别的一类.初学者容易在这方面犯错误,比如说我. 错题1 答案:C解析:每一个转义字符具有一个长度,这个字符串中:\t, \x43, \', \ ...
- English trip V1 - B 15. Giving Personal Information 提供个人信息 Teacher:Solo Key: Do/Does
In this lesson you will learn to answer simple questions about yourself. 本节课讲学到回答关于自己的一些简单问题 课上内容(L ...