Runnable是一个没有返回值的异步方法, 但是Callable有返回值
Callable源码
@FunctionalInterface
public interface Callable<V> {
V call() throws Exception;
}
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;
}
FutureTask
java核心技术卷2的示例使用的是FutureTask, 并且FutureTask实现了Future的接口. 似乎这个会比较好, 所以用这个写demo
public class CallableTest {
public static void main(String[] args) throws Exception {
Callable<Integer> callable = new CallableImpl();
FutureTask<Integer> futureTask = new FutureTask<>(callable);
Thread thread = new Thread(futureTask);
thread.start();
// 阻塞5秒, 等待子线程执行完
System.out.println(futureTask.get());
// 上面拿到了返回值, 才进行下一步操作
System.out.println("success");
}
}
class CallableImpl implements Callable<Integer> {
@Override
public Integer call() throws Exception {
Thread.sleep(5000);
return 1;
}
}
其他api测试