java中callable和future的关系

1. Callable 接口

Callable 接口和 Runnable 接口类似,但 Callable 接口可以返回一个值,并且可以抛出异常。可以使用 Callable 接口实现带返回值的多线程程序。Callable 接口定义如下:

@FunctionalInterface
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;
}

2. Future 接口

Future 接口用于表示一个异步计算的结果(静态对象)。Future 接口提供了获取计算结果的方法。可以将计算任务提交给 ExecutorService 进行异步处理,并通过 Future 接口获得结果,定义:

public interface Future<V> {

    boolean cancel(boolean mayInterruptIfRunning);

    boolean isCancelled();

    boolean isDone();

    V get() throws InterruptedException, ExecutionException;

    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

3.使用示例

import java.util.concurrent.*;

public class CallableAndFutureExample {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 创建一个线程池
        ExecutorService executor = Executors.newFixedThreadPool(2);

        // 创建两个 Callable 对象
        Callable<Integer> task1 = () -> {
            // 模拟耗时操作
            Thread.sleep(1000);
            return 10;
        };

        Callable<String> task2 = () -> {
            // 模拟耗时操作
            Thread.sleep(2000);
            return "Hello, World!";
        };

        // 使用 submit() 方法提交 Callable 对象到线程池,并获取 Future 对象
        Future<Integer> future1 = executor.submit(task1);
        Future<String> future2 = executor.submit(task2);

        // 使用 get() 方法获取 Future 对象的结果
        Integer result1 = future1.get();
        String result2 = future2.get();

        // 处理结果
        System.out.println("Result 1: " + result1);
        System.out.println("Result 2: " + result2);

        // 关闭线程池
        executor.shutdown();
    }
}

4.总结

总的来说就是callable进行运算将结果放入future中,future.get来进行阻塞

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值