Callable是类似于Runnable的接口,实现Callable接口的类和实现Runnable的类都是可被其它线程执行的任务。
- Callable和Runnable有几点不同:
- (1)Callable规定的方法是call(),而Runnable规定的方法是run().
- (2)Callable的任务执行后可返回值,而Runnable的任务是不能返回值的。
- (3)call()方法可抛出异常,而run()方法是不能抛出异常的。
(4)运行Callable任务可拿到一个Future对象,可了解任务执行情况,可取消任务的执行,还可获取任务执行的结果。
Callable接口:
// V就是call函数的返回值类型 , 也与 Future 的类型一致
public interface Callable<V> {
V call() throws Exception;
}
一般情况下是配合ExecutorService来使用的:
public class TestCall implements Callable<String> {
private int i;
public TestCall(int i){
this.i=i;
}
public String call() throws Exception {
return Thread.currentThread().getName()+"----"+i;
}
public static void main(String[] args){
//newCachedThreadPool 重用以前构造的线程(如果线程可用)。如果现有线程没有可用的,
// 则创建一个新线程并添加到池中。终止并从缓存中移除那些已有 60 秒钟未被使用的线程。
ExecutorService executorService= Executors.newCachedThreadPool();
List<Future<String>> results=new ArrayList<Future<String>>();
for(int k=0;k<10;k++){
Future<String> future=executorService.submit(new TestCall(k));
results.add(future);
}
System.out.println("-------------------");
for(Future<String> fs:results){
try{
System.out.println(fs.get());
}catch (InterruptedException e){
e.printStackTrace();
}catch (ExecutionException e){
e.printStackTrace();
}
}
}
}
结果:
-------------------
pool-1-thread-1----0
pool-1-thread-2----1
pool-1-thread-3----2
pool-1-thread-4----3
pool-1-thread-5----4
pool-1-thread-2----5
pool-1-thread-5----6
pool-1-thread-3----7
pool-1-thread-1----8
pool-1-thread-5----9