通常我们创建线程使用new Thread 和实现Runnable接口,但是这两种方式有一个缺陷,就是不能返回线程执行的结果,Doug lea又给我们提供了另一种方式,实现Callable接口,Callable只有一个方法,它是有返回值的,也可以抛出异常,它的执行结果可以被Future拿到。
Future是一个接口,它可以对Callable任务的执行结果进行操作。
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参数决定一个开启的任务能否被中断,如果任务已经完成,不管mayInterruptIfRunning为true或false,结果都为false,即取消完成的任务会返回false。
isCancelled:判断任务是否被取消,如果任务在正常完成前被取消直接返回true。
isDone:表示当前任务或所有的任务是否已经完成,如果任务完成,返回true。
get:获取执行结果,在这个过程中线程会一直阻塞,直到任务执行完毕,如果在此过程中,线程被中断直接抛出异常。
callable和future获取结果:
ExecutorService es = Executors.newCachedThreadPool();
java.util.concurrent.Future<String> future = es.submit(new Callable<String>() {
int i = 0;
@Override
public String call() throws Exception {
System.out.println("子线程执行过程");
for (i = 0; i < 100; i++) {
i++;
}
return "num为:" + i;
}
});
System.out.println("主线程开始执行");
try {
System.out.println("主线程取得异步结果为"+future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
看一下执行结果:
主线程开始执行
子线程执行过程
主线程取得异步结果为num为:100
FutureTask是Future的实现类,它实现了两个接口,Runnable和Future,所以它可以作为Runnable被执行,也可以得到Future的返回值,这就是异步加载的好处,在这个线程执行的过程中,另一个线程会继续往下执行,不进行阻塞,如果是一个非常耗时的操作,这样我们就有效节省了时间,最后我们用Future获取结果。
callable和futuretask获取结果:
System.out.println("主线程doingthing");
FutureTask<Integer> futuretask = new FutureTask<>(new Callable<Integer>() {
public Integer call() throws Exception {
System.out.println("子线程执行");
int i = 0;
for (i = 0; i < 100; i++) {
i++;
}
return i;
}
});
es.execute(futuretask);
Thread.sleep(100);
System.out.println("主线程继续doing");
System.out.println("执行结果为"+futuretask.get());
执行结果:
主线程doingthing
子线程执行
主线程继续doing
执行结果为100
如果只使用到它的取消方法不使用返回结果,一般写成Future<?>形式并且返回null,在dubbo源码中记得有好几处这样的写法。