Runnable是执行工作的独立任务,但是它不返回任何值,如果希望任务完成后返回一个值。那么可以实现Callable接口而不是Runnable接口,Callable是具有类型参数的泛型,它的类型参数是call()而不是run()。并且必须使用ExecutorService.submit()提交任务
public class CallableBase implements Callable<String>{
private int id=1;
private String name="";
private static int rows=1;
public CallableBase(){}
public CallableBase(String name){
this.name=name;
}
@Override
public String call() throws Exception {
//System.out.println("id:" +id++);
return "this is a test class"+rows++;
}
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
/*
* submit会产生Future对象,
* 他用Callable返回的特定类型进行了参数化
*/
ArrayList<Future<String>> list = new ArrayList<Future<String>>();
for (int i = 0; i < 5; i++) {
list.add(service.submit(new CallableBase("")));
}
for (Future<String> r:list) {
try {
//可以干别的
r.isDone();//查询Future是否已经完成
System.out.println(r.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}finally{
service.shutdown();
}
}
}
}