- Future
调用get()阻塞等待结果返回
public class TestFuture {
public static class CountTask implements Callable {
@Override
public Object call() throws Exception {
Long sum = 0L;
for (int i = 0; i < 10; i++) {
sum += i;
}
return sum;
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
testFuture();
}
private static void testFuture() throws InterruptedException, ExecutionException {
ThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
Future future = executor.submit(new CountTask());
System.out.println("执行计算任务中");
System.out.println(future.get()); // 阻塞等待结果
System.out.println("执行计算完成了");
}
}
以后应该会用的越来越少
该博客演示了一个Java程序,它利用`Future`和`ExecutorService`来提交一个计算任务并阻塞等待结果。`CountTask`实现了`Callable`接口,用于计算1到10的和。在`main`方法中,创建了一个单线程的`ScheduledThreadPoolExecutor`,提交任务并调用`future.get()`获取计算结果,输出后显示计算完成。
1615

被折叠的 条评论
为什么被折叠?



