今天复习Thinking in Java的带返回值的线程。
public class ThreadWithReturn {
//Runnable接口是执行工作的独立任务,但是它不反悔任何值。
//如果你希望你的任务在完成时能够返回一个值,那么可以实现Callable接口
//实现Callable接口
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 static void main(String[] args) {
ThreadWithReturn twr = new ThreadWithReturn();
//并且必须使用ExecutorService.submit()方法调用
ExecutorService exec = Executors.newCachedThreadPool();
List<Future<String>> results = new ArrayList<Future<String>>();
for(int i=0;i<10;i++){
results.add(exec.submit(twr.new TaskWithResult(i)));
}
for(Future<String> fs :results){
try{
//阻塞直到完成
System.out.println(fs.get());
} catch (InterruptedException e) {
e.printStackTrace();
return;
}catch(ExecutionException e){
e.printStackTrace();
return;
}
finally{
exec.shutdown();
}
}
//submit方法会产生Future对象,它用Callable返回特定类型进行了参数优化。
//可以使用isDone()方法来查询Future是否已经完成。
//当任务完成时,你可以调用get()方法获取结果值。
//如果不判定isDone()就直接调用get()方法,get()将会发生阻塞。
}
}