- 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("执行计算完成了");
}
}
以后应该会用的越来越少