Callable接口使用以及计算斐波那契数字的数值总和

本文通过具体示例展示了如何使用Callable接口与Future来获取多线程执行结果,并提供了一个计算斐波那契数列和的附加示例。此外,文章还介绍了如何利用ExecutorService来管理和控制线程池。

一、简单使用

Runnable是执行工作的独立任务,但是它不返回任何值。如果你希望任务完成的时能够返回一个值,那么可以实现一个Callable接口。在Java SE5中引入的Callable是一种具有类型参数的泛型,它的类型参数表示的是从call()方法中返回的值,并且必须用ExecutorService.submit()方法调用它。下面是一个简单的例子(摘自Java编程思想)

class TaskWithResult implements Callable<String> {
    private int id;

    public TaskWithResult(int id) {
        this.id = id;
    }

    @Override
    public String call() throws Exception {
        return "Result of TaskWithResult" + id;
    }
}

public class CallableDemo {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        ArrayList<Future<String>> results = new ArrayList<>();
        for (int i = 0;i<10;i++){
            results.add(executorService.submit(new TaskWithResult(i)));
        }
        for (Future<String> f: results){
            try {
                System.out.println(f.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }finally {
                executorService.shutdown();
            }
        }
    }
}

执行的结果如下

Result of TaskWithResult0
Result of TaskWithResult1
Result of TaskWithResult2
Result of TaskWithResult3
Result of TaskWithResult4
Result of TaskWithResult5
Result of TaskWithResult6
Result of TaskWithResult7
Result of TaskWithResult8
Result of TaskWithResult9

二、计算斐波那契数字的数值总和
public class FibonacciSumDemo {
    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        ArrayList<Future<Integer>> results = new ArrayList<Future<Integer>>();
        for (int i = 1; i <= 6; i++) results.add(exec.submit(new FibonacciSum(i)));
        Thread.yield();
        exec.shutdown();
        for (Future<Integer> fi : results)
            try {
                System.out.println(fi.get());
            } catch (Exception e) {
                e.printStackTrace();
            }
    }
}

class FibonacciSum implements Generator<Integer>, Callable<Integer> {
    private int count;
    private final int n;

    public FibonacciSum(int n) {
        this.n = n;
    }

    public Integer next() {
        return fib(count++);
    }

    private int fib(int n) {
        if (n < 2) return 1;
        return fib(n - 2) + fib(n - 1);
    }

    public Integer call() {
        int sum = 0;
        for (int i = 0; i < n; i++)
            sum += next();
        return sum;
    }
}

Generator接口定义如下

public interface Generator<T> {
    T next();
}

执行结果如下:

1
2
4
7
12
20

转载于:https://www.cnblogs.com/WangHaiMing/p/7674371.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值