Callable接口使用以及計算斐波那契數字的數值總和

1、簡單使用

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();
            }
        }
    }
}

執行的結果以下ide

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

2、計算斐波那契數字的數值總和

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接口定義以下this

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

執行結果以下:code

1
2
4
7
12
20
相關文章
相關標籤/搜索