并发编程——Future

该博客演示了一个Java程序,它利用`Future`和`ExecutorService`来提交一个计算任务并阻塞等待结果。`CountTask`实现了`Callable`接口,用于计算1到10的和。在`main`方法中,创建了一个单线程的`ScheduledThreadPoolExecutor`,提交任务并调用`future.get()`获取计算结果,输出后显示计算完成。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 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("执行计算完成了");
    }
}

以后应该会用的越来越少

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值