介绍
Java里面我们想创建一个线程一般是继承thread或者实现Runnable接口,然后在run方法里面去实现线程的业务逻辑,这两种方法是在执行完之后,线程不会返回结果的。因为run方法是void的。如果想要获取线程执行完的状态就得添加一些全局变量。但是这样的操作也不好,比如我们想要使用一个线程去异步获取一个东西,获取完之后再将结果返回出来。这种业务使用继承thread和实现runnable接口都不好实现。于是就诞生了Callable和Future。
示例代码
public class Demo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executor = Executors.newCachedThreadPool();
Future<String> future = executor.submit(new Callable<String>() {
@Override
public String call() throws Exception {
System.out.println("Call function ");
TimeUnit.SECONDS.sleep(1);
return "response";
}
});
System.out.println(future.get());
}
}
//运行输出结果如下:
Call function
response
我们来分析一下上面这个简单的Demo代码
首先创建了一个线程池newCachedThreadPool来执行任务。
然后提交一个Callable 任务,Callable任务打印一个字符串,线程等待一秒,然后返回一个字符。
Main线程拿到Callable任务return的结果。将结果打印出来。
这个简单的示例代码就演示了我们如何使用Callable和Future来实现带有返回结果的线程。并获取返回结果然后进行处理。
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;
}
Callable接口
public interface Callable<V> {
//带有返回值的call方法
V call() throws Exception;
}