Java并发编程-Future系列之Future的介绍和基本用法

本文介绍了Java中的Future接口,它表示异步计算的结果,提供了检查计算状态、获取结果和取消计算的方法。通过Future的get方法,可以在计算完成后获取结果,若未完成则会阻塞。此外,还讨论了Future的cancel方法以及如何结合ExecutorService实现异步任务执行和结果汇总。
摘要由CSDN通过智能技术生成


多线程(Multithreading)是Java的一个特性,它可以允许一个程序的多个部分(也就是线程)并发地执行,以达到最大程度利用CPU的目的。

关于多线程编程(Multithread Programming),下面介绍一下Future的特性和基本用法。

dogs_multithread_programming

About Future

Future(java.util.concurrent Interface Future<V>)表示异步计算的结果。Future接口提供了检查计算是否完成、检查计算是否被取消、等待计算完成并获取计算结果等方法。

A Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation. The result can only be retrieved using method get when the computation has completed, blocking if necessary until it is ready. Cancellation is performed by the cancel method. Additional methods are provided to determine if the task completed normally or was cancelled. Once a computation has completed, the computation cannot be cancelled. If you would like to use a Future for the sake of cancellability but not provide a usable result, you can declare types of the form Future<?> and return null as a result of the underlying task.

https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html

Future Methods

下面对Future的几个方法做一下简要介绍并提供代码演示。

private static ExecutorService executor = Executors.newSingleThreadExecutor();

public static Future<Integer> calculate(Integer input) {
   
    return executor.submit(() -> {
   
        Thread.sleep(3000);
         return input * input;
    });

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值