由于Runnable接口只能实现程序的操作无法返回数据,所以在需要返回结果的多线程操作中局限性就凸现出来。而Callable接口则可以实现结果的返回,同时Future则提供了线程任务的取消,查询是否完成,获取结果等。
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;
}
Callable接口提供了一个方法call()
,同时可以抛出异常。而在Runable中你只能捕获所有异常。
使用Callable一般配合线程池使用,比如ExecutorService接口声明了submit方法,用于提交Callable接口任务
<T> Future<T> submit(Callable<T> task);
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;
}
cancel
方法用来取消任务,如果取消任务成功则返回true,如果取消任务失败则返回false。参数mayInterruptIfRunning表示是否允许取消正在执行却没有执行完毕的任务,如果设置true,则表示可以取消正在执行过程中的任务。如果任务已经完成,则无论mayInterruptIfRunning为true还是false,此方法肯定返回false,即如果取消已经完成的任务会返回false;如果任务正在执行,若mayInterruptIfRunning设置为true,则返回true,若mayInterruptIfRunning设置为false,则返回false;如果任务还没有执行,则无论mayInterruptIfRunning为true还是false,肯定返回true。isCancelled
方法表示任务是否被取消成功,如果在任务正常完成前被取消成功,则返回 true。isDone
方法表示任务是否已经完成,若任务完成,则返回true;get()
方法用来获取执行结果,这个方法会产生阻塞,会一直等到任务执行完毕才返回;get(long timeout, TimeUnit unit)
用来获取执行结果,如果在指定时间内,还没获取到结果,就直接返回null。
Future 主要提供三个功能
1)任务完成判断
2)中断任务
3)获取任务结果
FutureTask
FutureTask是为我们提供的Future实现类,用于创建线程任务
public class FutureTask<V> implements RunnableFuture<V>
FutureTask实现RunnableFuture接口,顾名思义,该接口继承自Runnable和Future接口
public interface RunnableFuture<V> extends Runnable, Future<V> {
void run();
}
所以它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值
HelloWorld
public class CallableFutureTest {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(3);
Task task = new Task();
Future<Integer> submit = executorService.submit(task);
executorService.shutdown();
try{
Thread.sleep(1000);
}catch (Exception e) {
}
System.out.println(Thread.currentThread().getName()+":正在执行");
try {
System.out.println("线程执行结果"+submit.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
class Task implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println(Thread.currentThread().getName()+":正在执行");
Thread.sleep(3000);
int count =0;
for(int i=0;i<100;i++){
count += i;
}
return count;
}
}
多线程任务执行ExecutorService 提供了相应的方法
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
throws InterruptedException;
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException;
将任务放到集合中作为参数,同时返回List<Future<T>>
,集合返回值作为并发操作结果即可