一、Callable与Runnable的区别
1)Runnable是一个接口,里面只申明了一个run()方法,run()方法的返回值为void类型,因此,任务执行完后不会返回任何结果。
public interface Runnable {
public abstract void run();
}
2)Callable也是一个接口,里面也只申明了一个方法call(),该方法的返回值类型为一个泛型,是传递进来的V类型。
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
Future可以对具体的Callable任务或者Runnable进取消,查询是否取消,查询是否完成,通过get方法获取返回结果,该方法会阻塞,直到返回结果,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;
}
Future+Runnable示例代码:
public static void main(String[] args) {
ScheduledExecutorService executorService = Executors
.newSingleThreadScheduledExecutor();
Future<?> future = executorService.submit(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("睡眠1000毫秒");
}
});
// 取消任务
future.cancel(true);
try {
Thread.sleep(2000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 打印是否取消
System.out.println(future.isCancelled());
// 打印是否完成
System.out.println(future.isDone());
}
Future+Callable示例代码:
ScheduledExecutorService executorService = Executors
.newSingleThreadScheduledExecutor();
Future<String> future = executorService.submit(new Callable<String>() {
@Override
public String call() throws Exception {
return "Hello tailyou!";
}
});
// 取消任务
// future.cancel(true);
try {
System.out.println(future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
// 打印是否取消
System.out.println(future.isCancelled());
// 打印是否完成
System.out.println(future.isDone());
三、FutureTask
先看看FutureTask的源码:
public class FutureTask<V> implements RunnableFuture<V>
FutureTask实现了RunnableFuture,那么RunnableFuture又是什么玩意呢?再看看RunnableFuture的源码:
public interface RunnableFuture<V> extends Runnable, Future<V> {
void run();
}
RunnableFuture继承了Runnable接口和Future接口,因此它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值。FutureTask是Future的唯一实现类;
示例代码:
ScheduledExecutorService executorService = Executors
.newSingleThreadScheduledExecutor();
FutureTask<String> futureTask = new FutureTask<>(
new Callable<String>() {
@Override
public String call() throws Exception {
return "Hello tailyou!";
}
});
executorService.submit(futureTask);
try {
System.out.println(futureTask.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}