ThreadPoolExecutor + Callable + Future Example

来源:互联网 发布:sql注入绕过单引号 编辑:程序博客网 时间:2024/06/06 18:12

Executor框架的优点之一就在于它可以执行并行任务,而这些并行任务执行完成之后会返回一个结果。Java并发API通过两个接口Callable和Future来获取,下面简要介绍。
Callable:这个接口有一个call()方法。在这个方法中,你必须实现所要执行的任务的逻辑。Callable接口是一个泛型接口,因此,你需要指定返回值的类型。
Future:这个接口有一些方法来获取由Callable对象任务返回的结果并管理它的状态。

Callable源码:

public interface Callable<V> {    V call() throws Exception;}

Future源码:

public interface Future<V> {    boolean cancel(boolean mayInterruptIfRunning);    boolean isCancelled();    boolean isDone();    V get() throws InterruptedException, ExecutionException;    V get(long timeout, TimeUnit unit)        throws InterruptedException, ExecutionException, TimeoutException;}

示例:

在这个例子中,我会创建一个类型为Callable的类FactorialCalculator,重写call()方法,计算之后,返回结果。这个结果会被main函数中的Future引用获取。

完整代码CallableExample.java:

package MultiThread;import java.util.ArrayList;import java.util.List;import java.util.concurrent.*;class FactorialCalculator implements Callable<Integer> {    private Integer number;    public FactorialCalculator(Integer number){        this.number = number;    }    @Override    public Integer call() throws Exception {        int result = 1;        if ((number == 0) || (number == 1) ) {            result = 1;        } else {            for (int i=2; i<=number; i++) {                result *= i;            }        }        System.out.println("Result for number - " + number + " -> " + result);        return result;    }}public class CallableExample {    public static void main(String[] args) {        ThreadPoolExecutor executorService = (ThreadPoolExecutor)Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());        List<Future<Integer>> resultList = new ArrayList<Future<Integer>>();        for (int i = 0; i < 4; i++) {            Integer number = i + 1;            FactorialCalculator factorial = new FactorialCalculator(number);            Future<Integer> result = executorService.submit(factorial);            resultList.add(result);        }        System.out.println("Tasks submit finished.");        for (Future<Integer> future : resultList) {            try {                System.out.println("Future result is - " + " - " + future.get() + "; And Task Done is" +                        " " + future.isDone());            } catch (InterruptedException e) {                e.printStackTrace();            } catch (ExecutionException e) {                e.printStackTrace();            }        }        executorService.shutdown();    }} 


Output

Tasks submit finished.
Result for number - 1 -> 1
Future result is -  - 1; And Task Done is true
Result for number - 3 -> 6
Result for number - 4 -> 24
Result for number - 2 -> 2
Future result is -  - 2; And Task Done is true
Future result is -  - 6; And Task Done is true
Future result is -  - 24; And Task Done is true


说明几点:

1.这里你提交了一个Callable对象到submit()方法中,这个方法接收了Callable对象参数然后返回一个Future对象,由此你可以使用它达到两个目的:

a)你可以控制任务的状态:你可以取消任务然后判断它是否已经完成了。可以使用isDone()方法。

b)可以获取call()方法返回的结果:可以使用get()方法。get()方法一直等待直到Callable对象完成执行call()方法并且返回了结果。如果在get等待结果的过程中被中断,它会抛出InterruptedException异常。如果call()方法抛出一个异常,这方法会抛出一个Execution异常。

c)Future接口会提供另外一个版本的get()方法。get(longtimeout,TimeUnitunit)。这个get会等待特定的时间,如果特定的时间过了,依然没有结果返回,那么方法就会返回一个空值。



Author:忆之独秀

Email:leaguenew@qq.com

注明出处:http://blog.csdn.net/lavorange/article/details/77857744


原创粉丝点击