一、简单使用 |
Runnable是执行工作的独立任务,但是它不返回任何值。如果你希望任务完成的时能够返回一个值,那么可以实现一个Callable接口。在Java SE5中引入的Callable是一种具有类型参数的泛型,它的类型参数表示的是从call()方法中返回的值,并且必须用ExecutorService.submit()方法调用它。下面是一个简单的例子(摘自Java编程思想)
class TaskWithResult implements Callable{ 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 > results = new ArrayList<>(); for (int i = 0;i<10;i++){ results.add(executorService.submit(new TaskWithResult(i))); } for (Future f: results){ try { System.out.println(f.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); }finally { executorService.shutdown(); } } }}
执行的结果如下
Result of TaskWithResult0Result of TaskWithResult1Result of TaskWithResult2Result of TaskWithResult3Result of TaskWithResult4Result of TaskWithResult5Result of TaskWithResult6Result of TaskWithResult7Result of TaskWithResult8Result of TaskWithResult9
二、计算斐波那契数字的数值总和 |
public class FibonacciSumDemo { public static void main(String[] args) { ExecutorService exec = Executors.newCachedThreadPool(); ArrayList> results = new ArrayList >(); for (int i = 1; i <= 6; i++) results.add(exec.submit(new FibonacciSum(i))); Thread.yield(); exec.shutdown(); for (Future fi : results) try { System.out.println(fi.get()); } catch (Exception e) { e.printStackTrace(); } }}class FibonacciSum implements Generator , Callable { 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 next();}
执行结果如下:
12471220