Java基础之Callable、Future、FutureTask

随笔,笔记

Callable是与 Runable类似的一个接口,它支持参数化,只有一个方法 call

public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}

Future 保存异步计算的结果。可以启动一个计算,将Future 对象交给某个线程。Future 对象的所有者在结果计算好之后就可以获得它。

public interface Future<V> {
	// 取消计算,若还未开始,就不要开始;若以运行,并传入true 就中断。
    boolean cancel(boolean mayInterruptIfRunning);
    // 任务完成前被取消,返回 true
    boolean isCancelled();
    // 判断计算 是否完成,若完成则返回 true
    boolean isDone();
    // 方法会被 阻塞,直到计算完成。若线程中断 会抛出异常
    V get() throws InterruptedException, ExecutionException;
    // 方法被阻塞,若超时 会抛出TimeoutException。若线程被中断 则抛出InterruptedException
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

FutureTask 包装器,可将 Callable 转换为 FutureRunnable,它同时 实现二者的接口。

Callable<Integer> myComputation = ....;
FutureTask<Integer> task = new FutureTask<>(myComputation);
// 转换成 Runnable
Thread thread = new Thread(task);
thread.start();
// 转换为 Future
Integer integer = task.get();

Callable 与 学的 Runnable 差不多,只是 Callable 有返回值。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值