博客
关于我
简单看看线程池执行方法execute()和submit()方法的使用
阅读量:231 次
发布时间:2019-02-28

本文共 1469 字,大约阅读时间需要 4 分钟。

今天,我在学习Java的线程和线程池相关知识时,深入研究了ExecutorService中的execute和submit方法。这两个方法在功能上有细微差别,但理解它们的区别对于编写高效的并发代码至关重要。

首先,ExecutorService提供了两个主要方法:execute和submit。execute用于提交没有返回值的Runnable任务,而submit用于提交有返回值的Callable任务。两者的区别主要体现在任务执行和结果处理上。

为了更好地理解这两个方法的区别,我编写了一个简单的代码示例:

import java.util.concurrent.ExecutorService;import java.util.concurrent.Future;import java.util.concurrent.Executors;public class ExecutorServiceExample {    public static void main(String[] args) throws Exception {        ExecutorService executorService = Executors.newSingleThreadExecutor();        // 使用execute提交Runnable任务        executorService.execute(new Runnable() {            @Override            public void run() {                System.out.println("执行execute方法");            }        });        // 使用submit提交Callable任务,并获取返回值        Future
future = executorService.submit(new Callable
() { @Override public String call() throws Exception { System.out.println("执行submit方法"); return "执行submit方法"; } }); // 获取submit任务的结果 System.out.println(future.get()); }}

运行此代码,输出结果如下:

执行execute方法执行submit方法执行submit方法

从输出可以看出,execute方法提交的任务会立即执行,但不会等待结果。而submit方法提交的任务会执行并返回结果,可以通过Future对象获取。

总结

通过上述例子,我理解了execute和submit方法的主要区别:

  • execute方法

    • 适用于不需要返回值的任务。
    • 任务执行后不会等待结果。
    • 不返回任何值。
  • submit方法

    • 适用于需要返回值的任务。
    • 任务执行后会等待并返回结果。
    • 返回一个Future对象,用于获取任务结果。
  • 这种理解有助于在实际开发中选择合适的方法来处理不同类型的任务。无论是哪种方法,都可以通过Future对象等待任务完成,这使得代码更加灵活和高效。

    转载地址:http://abjp.baihongyu.com/

    你可能感兴趣的文章
    Nginx配置实例-负载均衡实例:平均访问多台服务器
    查看>>
    Nio ByteBuffer组件读写指针切换原理与常用方法
    查看>>
    NIO Selector实现原理
    查看>>
    NISP一级,NISP二级报考说明,零基础入门到精通,收藏这篇就够了
    查看>>
    NI笔试——大数加法
    查看>>
    NLP 基于kashgari和BERT实现中文命名实体识别(NER)
    查看>>
    Nmap扫描教程之Nmap基础知识
    查看>>
    NMAP网络扫描工具的安装与使用
    查看>>
    NN&DL4.3 Getting your matrix dimensions right
    查看>>
    NN&DL4.8 What does this have to do with the brain?
    查看>>
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>
    No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
    查看>>
    No new migrations found. Your system is up-to-date.
    查看>>
    No qualifying bean of type XXX found for dependency XXX.
    查看>>
    No resource identifier found for attribute 'srcCompat' in package的解决办法
    查看>>
    No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
    查看>>