首页  

ExecutorService中submit和execute的区别     所属分类 java 浏览量 1225
1  execute在 Executor 里定义
   void execute(Runnable command)
   submit在 Executor 的子类ExecutorService里定义
   
        Future submit(Callable task)
        Future submit(Runnable task, T result)
       Future submit(Runnable task)

2  execute方法无返回值
   submit 方法返回 Future 可以获取结果 取消任务 获取任务执行异常
   
3  execute 执行任务抛出未处理异常 会导致工作线程退出
   submit  执行任务抛异常 内部会拦截处理 不会导致工作线程退出 future.get 会抛出包装后的异常 ExecutionException
   
   
   Future接口实现类 FutureTask 
   
    public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);
        return report(s);
    }
    
    private V report(int s) throws ExecutionException {
        Object x = outcome;
        if (s == NORMAL)
            return (V)x;
        if (s >= CANCELLED)
            throw new CancellationException();
        throw new ExecutionException((Throwable)x);
    }
    

SubmitExecuteTest 测试代码说明
启动只有一个线程的线程池 
使用 execute 运行任务 ,任务抛出异常后,工作线程退出,线程池自动启动新的线程(线程名字会变)
使用 submit 运行任务 ,任务抛出异常后,工作线程不会退出, 工作线程名一直不变
调用future get方法会抛出 包装后的异常 


具体代码

https://gitee.com/dyyx/hellocode/blob/master/src/dyyx/conc/SubmitExecuteTest.java

上一篇     下一篇
互联网新老词汇对照表

NoClassDefFoundError和ClassNotFoundException异常的区别

进程线程与协程的区别

java thread join实现原理

java线程池shutdown和shutdownNow的区别

JAVA虚拟机关闭钩子Shutdown Hook使用