最近看同事的代码,他们在一个项目中用到了java的excutor框架,我也参考了《java并发编程实践》这本书,将相应的知识点看了看。callable和Future的一些内容总结如下:
Callable与 Future 两功能是Java 5版本中加入的,Callable是类似于Runnable的接口,实现Callable接口的类和实现Runnable的类
都是可被其他线程执行的任务。
Callable的接口定义如下:
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;
}
Callable和Runnable的区别如下:
I Callable定义的方法是call,而Runnable定义的方法是run。
II Callable的call方法可以有返回值,而Runnable的run方法不能有返回值。
III Callable的call方法可抛出异常,而Runnable的run方法不能抛出异常。
Future 介绍
Future表示异步计算的结果,它提供了检查计算是否完成的方法,以等待计算的完成,并检索计算的结果。Future的cancel方法可以取消任务的执行,它有一布尔参数,参数为 true 表示立即中断任务的执行,参数为 false 表示允许正在运行的任务运行完成。Future的 get 方法等待计算完成,获取计算结果。
下面的示例中,我们使用Callable来提交任务,使用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;
}
程序验证:
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ExecutorService threadPool = Executors.newSingleThreadExecutor();
Future<String> future = threadPool.submit(new Callable<String>() {
public String call() throws Exception {
Thread.sleep(2000);
return "Hello";
};
});
System.out.println("Wait for result...");
try {
System.out.println("Get the result:" + future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
threadPool.shutdown();
}
}
运行结果:
Wait for result...
Get the result:Hello