一 理论
Runnable是执行工作的独立任务,但是不返回任何值。如果我们希望任务完成之后有返回值,可以实现Callable接口。在JavaSE5中引入的Callable是一个具有类型参数的范型,他的类型参数方法表示为方法call()而不是run()中返回的值,并且必须使用ExecutorService.submint()方法进行调用。
二 示例
//实现接口Callable 参数类型是String
public 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;
}
}
//java测试方法,基于junit4
@Test
public void main2() {
ExecutorService exec= Executors.newCachedThreadPool();
//Future接口后面有源码
ArrayList<Future<String>> results=new ArrayList<Future<String>>();
long start=System.currentTimeMillis();
for(int i=0;i<10;i++){
results.add(exec.submit(new TaskWithResult(i)));
}
//System.out.println("====================cost:"+(System.currentTimeMillis()-start));
int count=0;
//遍历数据
for(Future<String> fs:results){
//System.out.println("========cost:"+(System.currentTimeMillis()-start));
long start2=System.currentTimeMillis();
try{
//取数据
System.out.println(fs.get());
}catch (InterruptedException e){
System.out.print(e);
}catch (ExecutionException e){
System.out.print(e);
}finally {
exec.shutdown();
}
//System.out.println((count++)+"====================cost:"+(System.currentTimeMillis()-start2));
}
}
执行结果如下图:
result.png
三Callable接口源码
@FunctionalInterface
public interface Callable<V> {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
V call() throws Exception;
}
四 Future 接口源码
public interface Future<V> {
//取消
boolean cancel(boolean mayInterruptIfRunning);
boolean isCancelled();
//任务是否完成
boolean isDone();
//获得数据
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
网友评论