线程池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来捕获这个异常。

猜你喜欢

转载自blog.csdn.net/liuguang212/article/details/106549036