当前位置: 代码网 > it编程>编程语言>Java > 线程池之exectue与submit的区别及说明

线程池之exectue与submit的区别及说明

2024年08月06日 Java 我要评论
1、参数及返回值不同excute只能提交runnable,无返回值submit既可以提交runnable,返回值为null,也可以提交callable,返回值futureexcute:submit:

1、参数及返回值不同

  • excute只能提交runnable,无返回值
  • submit既可以提交runnable,返回值为null,也可以提交callable,返回值future

excute:

submit:

2、异常抛出不同

  • execute执行任务时遇到异常会直接抛出
  • submit执行任务是遇到异常不会直接抛出,只有在使用future的get方法获取返回值时才会抛出异常

execute:

import org.junit.test;
 
import java.util.concurrent.*;
 
public class threadpooldemo {
 
    @test
    public void test() throws interruptedexception, executionexception {
        //创建线程池对象
        executorservice singlethreadexecutor = executors.newsinglethreadexecutor();
        singlethreadexecutor.execute(() -> {
            system.out.println("开始");
            int i = 10 / 0;
            system.out.println("结束");
        });
    }
}

输出:

开始
exception in thread "pool-1-thread-1" java.lang.arithmeticexception: / by zero
at threadpooldemo.lambda$test$0(threadpooldemo.java:13)
at java.util.concurrent.threadpoolexecutor.runworker(threadpoolexecutor.java:1149)
at java.util.concurrent.threadpoolexecutor$worker.run(threadpoolexecutor.java:624)
at java.lang.thread.run(thread.java:748)

submit:

import org.junit.test;
 
import java.util.concurrent.*;
 
public class threadpooldemo {
 
    @test
    public void test() throws interruptedexception, executionexception {
        //创建线程池对象
        executorservice singlethreadexecutor = executors.newsinglethreadexecutor();
        singlethreadexecutor.submit(() -> {
            system.out.println("开始");
            int i = 10 / 0;
            system.out.println("结束");
        });
    }
}

输出:

开始

submit 增加future的get方法

import org.junit.test;
 
import java.util.concurrent.*;
 
public class threadpooldemo {
    @test
    public void test() throws interruptedexception, executionexception {
        //创建线程池对象
        executorservice singlethreadexecutor = executors.newsinglethreadexecutor();
        future future=singlethreadexecutor.submit(() -> {
            system.out.println("开始");
            int i = 10 / 0;
            system.out.println("结束");
        });
        object o=future.get();
        singlethreadexecutor.shutdown();
    }
}
 

输出:

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com