线程池ThreadPoolExecutor中execute和submit方法对比

在研究ThreadPoolExecutor线程池的时候,发现可以有两种启动线程的方法:submit(Callable callable ),excute(Runnable runnable)
先说个结论吧:

  1. submit(Callable x)方法 可以提供Future < T > 类型的返回值。可以用这个future来判断任务是否成功完成。——实现Callable接口
  2. execute(Runnable x) 没有返回值。可以执行任务,但无法判断任务是否成功完成。——实现Runnable接口

submit方法和execute方法都可以用来提交任务给线程池去执行,但是两者有一些区别,如下:

1、定义方法的类不同

execute()方法是在ThreadPoolExecutor类中定义的。
submit() 是在ExecutorService接口中定义的

2、返回值类型不同

execute方法返回值为空
submit方法会以Future的形式返回线程的执行结果。

3、对异常的处理方式不同

如果执行的任务中产生了异常,execute方法会直接打印产生的异常的堆栈,由于该异常是在子线程中产生的,主线程中包围在execute方法周围的try-catch语句并不能捕获该异常。

4 示例

/**
 * @author lg
 * @date 6-4
 */
public class ThreadTest {
    public static void main(String[] args){
        aaa();
    }
    
    public static void aaa(){
        List<Integer> age1 = new ArrayList<>();
        List<Integer> age2 = new ArrayList<>();
        List<Integer> age3 = new ArrayList<>();
        age1.add(0);
        age1.add(3);
        age1.add(6);
        age2.add(3333);
        age2.add(4234234); age2.add(33); age3.add(2); age3.add(5); age3.add(6666666); age3.add(8);
        List<List<Integer>> lists = new ArrayList<>();
        lists.add(age1);
        lists.add(age2);
        lists.add(age3);
        //核心线程数
        int corePoolsize=5;
        //最大线程数量
        int maxThreadPoolsize=30;
        //空闲时间
        long keepAliveTime=600;
        //队列
        BlockingQueue<Runnable> workQueue = new SynchronousQueue<Runnable>();
        //单位
        TimeUnit unit=TimeUnit.SECONDS;
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        //拒绝策略
        RejectedExecutionHandler rejectedExecutionHandler=new ThreadPoolExecutor.CallerRunsPolicy();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolsize, maxThreadPoolsize, keepAliveTime, unit, workQueue, threadFactory, rejectedExecutionHandler);

        for (List<Integer> age:lists){
            Future submit = threadPoolExecutor.submit(new checkbyHand(age));
            try {
                List<Integer> o = (List<Integer>) submit.get();
                o.forEach(System.out::println);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        System.out.println("-----------------");
        for (List<Integer> age:lists){
            threadPoolExecutor.execute(new checkbyHandTwo(age));
        }
        threadPoolExecutor.shutdown();
        while (true) {//等待所有任务都执行结束
            if (threadPoolExecutor.isTerminated()) {//所有的子线程都结束了
                break;
            }
        }
    }
    public static class checkbyHand implements Callable{
        private List<Integer> age;

        public checkbyHand(List<Integer> age) {
            this.age = age;
        }

        @Override
        public Object call() throws Exception {
            Collections.sort(age);
            return age;
        }
    }
    public static class checkbyHandTwo implements Runnable{
        private List<Integer> age;

        public checkbyHandTwo(List<Integer> age) {
            this.age = age;
        }

        @Override
        public void run() {
            Collections.sort(age);
            System.out.println(age);
        }
    }

}

结论

1.execute方法执行线程,线程产生的异常会在线程池内部被消耗,execute方法外面并不能捕获到异常;
2.submit方法执行线程,得到一个future,如果不去尝试获取future的内容,不会有异常抛出。实际上,future的生成是瞬时, 相当于得到一个占位符,具体的操作要去调用future的API才会执行;
3. submit方法执行线程得到一个future,如果调用这个future的API去获取结果,例如future.get(),如果线程中有异常产生,就可以通过在submit方法周围环绕try…catch来捕获这个异常。

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
线程池submit()和execute()方法都可以用来将任务提交到线程池,但是它们有一些不同之处。 submit()方法是ExecutorService接口定义的方法,它返回一个Future对象,可以用来获取任务的执行结果或者取消任务的执行。submit()方法可以接受Runnable和Callable类型的参数。 execute()方法ThreadPoolExecutor定义的方法,它没有返回值,也不能获取任务的执行结果或者取消任务的执行。execute()方法只能接受Runnable类型的参数。 在实际使用,一般使用submit()方法来提交任务,因为它可以更好地控制任务的执行情况,比如可以通过Future对象来获取任务的执行结果,或者通过cancel()方法来取消任务的执行。而execute()方法更适合一些简单的任务,比如打印日志等。 下面是submit()方法的使用示例: ```java ExecutorService executorService = Executors.newFixedThreadPool(10); Future<String> future = executorService.submit(new Callable<String>() { @Override public String call() throws Exception { return "Hello, World!"; } }); String result = future.get(); System.out.println(result); executorService.shutdown(); ``` 下面是execute()方法的使用示例: ```java ThreadPoolExecutor executorService = new ThreadPoolExecutor(10, 10, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); executorService.execute(new Runnable() { @Override public void run() { System.out.println("Hello, World!"); } }); executorService.shutdown(); ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值