java.util.concurrent
提供Callable
和Future
接口.
我们知道Runnable
接口无法返回线程执行的结果,而Callable
可以解决该问题,其返回值可以被Future
捕捉到,换句话说,Future
可以获得异步任务的返回值.
public class CallableAndFuture {
public static void main(String[] args) {
Callable<Integer> callable = new Callable<Integer>() {
public Integer call() throws Exception {
return new Random().nextInt(100);
}
};
FutureTask<Integer> future = new FutureTask<Integer>(callable);
new Thread(future).start();
try {
Thread.sleep(5000);// 可能做一些事情
System.out.println(future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
FutureTask
实现Future
和Runnable
接口,这种结合带来什么好处呢,假如有个很耗时的返回值需要计算,并且这个返回值不是立刻需要的话,我们可以利用该组合;使用其他线程来计算返回值,而当前线程在使用返回值前可以执行其他操作,等需要这个返回值时,通过Future
得到.
另外我们还可以通过ExecutorService来使用Future和Callable
public class CallableAndFuture {
public static void main(String[] args) {
ExecutorService threadPool = Executors.newSingleThreadExecutor();
Future<Integer> future = threadPool.submit(new Callable<Integer>() {
public Integer call() throws Exception {
return new Random().nextInt(100);
}
});
try {
Thread.sleep(5000);// 可能做一些事情
System.out.println(future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
threadPool.shutdown();
}
}