submit()和execute()区别

在这里插入图片描述
在这里插入图片描述

1、接收的参数不同

由以上图看出,execute()只能接受Runnable类型参数,而submit()函数还可以接受Callable类型参数;

2、有无返回值

submit()函数都有返回值Future,而execute()函数没有返回值;

3、submit()方便exception处理

submit()函数可以通过Future.get()函数可以判断任务是不是执行完成;
如果在task里会抛出checked或者unchecked exception,而又希望外面的调用者能够感知这些exception并做出及时的处理,那么就需要用到submit,通过捕获Future.get抛出的异常。

class RunnableTest implements Runnable{
    private String taskName;
    public RunnableTest(final String taskName){
        this.taskName=taskName;
    }

    public void run(){
        System.out.println("inside "+taskName);
        throw new RuntimeException("exception from "+taskName);
    }
}

public class submitVSexecute {
    public static void main(String[] args) {
        ExecutorService pool=Executors.newFixedThreadPool(2);
        pool.execute(new RunnableTest("task1"));

        Future task2 = pool.submit(new RunnableTest("task2"));
        try{
            if(task2.get()==null){
                System.out.println("任务完成");
            }
        }catch(InterruptedException e){

        }catch(ExecutionException e){
            System.out.println(e.getCause().getMessage());
        }
    }
}

在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值