从任务中发生返回值

从任务中产生返回值
Runnable接口不返回任何值,如果希望任务完成时能返回一个值,可以实现Callable接口。
   1.Callable是一个类型参数的接口,类型参数表示从方法call()中的返回值。
   2.运行时必须使用ExecutorService.submit去调用它,例子如下:

public class TaskWithResults implements Callable<String>{

private int id;

public TaskWithResults(int id) {
// TODO Auto-generated constructor stub
this.id=id;
}

@Override
public String call() throws Exception {
// TODO Auto-generated method stub
return "results of TaskWithResults "+id;
}

}

===========================================
public class CallableDemo {


public static void main(String[] args)
{
ExecutorService exec=Executors.newCachedThreadPool();
ArrayList<Future<String>> results=new ArrayList<Future<String>>();
for(int i=0;i<10;i++)
results.add(exec.submit(new TaskWithResults(i)));
for(Future<String> fs:results )
{
try {
System.out.println(fs.get());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally
{
exec.shutdown();
}
}
}

}