代码改变世界

第一章:多线程八之向线程池提交任务的两种方式

2023-10-15 17:07  阿方技术圈  阅读(283)  评论(0)    收藏  举报

向线程池提交任务的两种方式大致如下:

       方式一:调用execute()方法

     //Executor 接口中的方法
     void execute(Runnable command);

  方式二:调用submit()方法

     //ExecutorService 接口中的方法
     <T> Future<T> submit(Callable<T> task); 
     <T> Future<T> submit(Runnable task, T result);
     Future<?> submit(Runnable task);

  submit()和execute()两类方法的区别

(1)二者所接收的参数不一样Execute()方法只能接收Runnable类型的参数,而submit()方法可以接收Callable、Runnable两种类型的参数。Callable类型的任务是可以返回执行结果的,而Runnable类型的任务不可以返回执行结果。Callable是JDK 1.5加入的执行目标接口,作为Runnable的一种补充,允许有返回值,允许抛出异常。Runnable和Callable的主要区别为:Callable允许有返回值,Runnable不允许有返回值;Runnable不允许抛出异常,Callable允许抛出异常。

(2)submit()提交任务后会有返回值,而execute()没有execute()方法主要用于启动任务的执行,而任务的执行结果和可能的异常调用者并不关心。submit()方法也用于启动任务的执行,但是启动之后会返回Future对象,代表一个异步执行实例,可以通过该异步执行实例去获取结果。

(3)submit()方便Exception处理execute()方法在启动任务执行后,任务执行过程中可能发生的异常调用者并不关心。而通过submit()方法返回的Future对象(异步执行实例),可以进行异步执行过程中的异常捕获。

 @Test
    public void testSubmitDemo()
    {
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(2);
        Future<Integer> future = pool.submit(new Callable<Integer>()
        {

            @Override
            public Integer call() throws Exception {
                return RandomUtils.nextInt(200,300);
            }
        });

        try
        {
            Integer result = future.get();
            System.out.println("异步执行的结果是:" + result);
        } catch (InterruptedException e)
        {
            System.out.println("异步调用被中断");
            e.printStackTrace();
        } catch (ExecutionException e)
        {
            System.out.println("异步调用过程中,发生了异常");
            e.printStackTrace();
        }
        Thread.sleep(10);
        //关闭线程池
        pool.shutdown();
    }

  执行结果

 在ThreadPoolExecutor类的实现中,内部核心的任务提交方法是execute()方法,虽然用户程序通过submit()也可以提交任务,但是实际上submit()方法中最终调用的还是execute()方法。

 public <T> Future<T> submit(Callable<T> task) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<T> ftask = newTaskFor(task);
        execute(ftask);
        return ftask;
    }