并发编程之Callable、Runnable、Future与FutureTask


前言

在 Java 中,Callable、Future 和 FutureTask 是用于实现多线程编程和异步任务处理的重要接口和类。

一、Callable与Runnable

1.1 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;
}

注解是函数式接口,意味着可以用lambda表达式更简洁地使用它。Callable是个泛型接口,只有一个方法call,方法的返回类型是传递进来的V类型。call方法还支持抛出异常。

1.2 Runnable

@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

和Callable非常相似,同样是函数式接口,只有一个方法run,没有返回类型。

1.3 二者对比

  • 返回结果
    Callable 接口中的 call() 方法可以返回结果,并且可以抛出受检异常。这使得 Callable 更适合于需要返回结果的任务。
    Runnable 接口的 run() 方法没有返回值,只能通过外部变量或其他方式来传递任务执行的结果。
  • 异常处理
    Callable 接口的 call() 方法可以抛出受检异常,而 Runnable 接口的 run() 方法只能捕获异常并在方法内部处理。
    这使得 Callable 在处理异常时更加灵活,可以通过 throws 关键字声明受检异常。
  • 线程池提交
    Callable 接口通常与 ExecutorService 结合使用,可以通过 ExecutorService.submit() 方法提交 Callable 任务,并获取返回的 Future 对象来获取结果。
    Runnable 接口也可以通过 ExecutorService 提交任务,但无法直接获取任务执行的结果,需要通过其他方式来实现结果的传递和处理。
  • 适用场景
    Callable 适用于需要返回结果、处理异常以及更复杂任务逻辑的场景,例如需要执行计算、查询数据库等操作。
    Runnable 适用于简单的并发任务,不需要返回结果或处理异常的场景,例如执行简单的耗时操作或更新 UI 界面等。

关于线程池提交这一点,看一下ExecutorService的submit()相关重载方法:

首先ExecutorService 继承自Executor,而Executor是一个接口,Executor 接口定义了一个 execute() 方法,用于执行给定的任务(即 Runnable 对象)。该方法没有返回值,只是负责接收一个 Runnable 任务,并在将来的某个时间执行该任务。

public interface ExecutorService extends Executor {
public interface Executor {

    /**
     * Executes the given command at some time in the future.  The command
     * may execute in a new thread, in a pooled thread, or in the calling
     * thread, at the discretion of the {@code Executor} implementation.
     *
     * @param command the runnable task
     * @throws RejectedExecutionException if this task cannot be
     * accepted for execution
     * @throws NullPointerException if command is null
     */
    void execute(Runnable command);
}
    <T> Future<T> submit(Callable<T> task);
    <T> Future<T> submit(Runnable task, T result);
    Future<?> submit(Runnable task);
  • submit(Callable<T> task)
    这个方法接收一个 Callable 对象作为参数,表示需要执行的任务,并返回一个 Future 对象。
    Callable 接口的泛型类型 T 表示任务执行完毕后的返回结果类型。
    返回的 Future 对象可以用于获取任务执行的结果,可以通过 Future.get() 方法来获取任务执行的结果,该方法会阻塞直到任务执行完毕并返回结果。
  • submit(Runnable task, T result)
    这个方法接收一个 Runnable 对象和一个泛型类型 T 的参数作为任务和结果,并返回一个 Future 对象。
    该方法会执行给定的 Runnable 任务,并将结果作为参数传递给 Future 对象。
    返回的 Future 对象可以用于获取任务执行的状态,但无法获取具体的结果。如果需要获取结果,可以调用 Future.get() 方法,但只能获取到传入的结果对象。
  • submit(Runnable task)
    这个方法接收一个 Runnable 对象作为参数,表示需要执行的任务,并返回一个 Future 对象。
    由于 Runnable 接口的 run() 方法没有返回值,因此这种情况下返回的 Future 对象的类型是 Future<?>,表示无法确定任务的返回结果类型。
    返回的 Future 对象可以用于获取任务执行的状态,但无法获取具体的结果。

submit()重载方法,都返回了Future,但是只有参数为Callable类型的方法返回的Future结果最完整, 接下来看一下Future


二、Future与FutureTask

2.1 Future

Future是一个接口,对于具体的Runnable或者Callable任务的执行结果进行取消、查询是否完成、获取结果等操作。必要时可以通过get方法获取执行结果,该方法会阻塞直到任务返回结果

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;
}
  • cancel(boolean mayInterruptIfRunning)
    cancel() 方法用于尝试取消任务的执行。如果任务已经完成、已经被取消或者由于其他原因无法取消,则此方法返回 false。
    参数 mayInterruptIfRunning 表示是否应该中断正在执行的任务。如果任务已经开始执行并且被中断,则返回 true;否则返回 false。
  • isCancelled()
    isCancelled方法表示任务是否被取消成功,如果在任务正常完成前被取消成功,则返回 true。
  • isDone()
    isDone() 方法用于检查任务是否已经完成。如果任务已经完成(无论是正常完成、被取消还是由于异常完成),则返回 true;否则返回 false。
  • get() throws InterruptedException, ExecutionException:
    get() 方法用于获取任务的执行结果。如果任务已经完成,则立即返回结果;如果任务尚未完成,则会阻塞当前线程直到任务完成。
    如果任务被取消,会抛出 CancellationException 异常;如果任务执行过程中出现异常,会抛出 ExecutionException 异常;如果在等待过程中当前线程被中断,会抛出 InterruptedException 异常。
  • get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException:
    get(long timeout, TimeUnit unit) 方法与 get() 方法类似,但增加了超时参数,指定最长等待时间。
    如果在指定的超时时间内任务完成,则返回结果;如果超时仍未完成,则抛出 TimeoutException 异常。
    其他异常情况与 get() 方法相同,可能抛出 InterruptedException 和 ExecutionException 异常。

2.2 FutureTask

FutureTask类实现了RunnableFuture接口,我们看一下RunnableFuture接口的实现:

public class FutureTask<V> implements RunnableFuture<V> {

RunnableFuture继承了Runnable接口和Future接口,而FutureTask实现了RunnableFuture接口。所以它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值。

public interface RunnableFuture<V> extends Runnable, Future<V> {
    /**
     * Sets this Future to the result of its computation
     * unless it has been cancelled.
     */
    void run();
}

看一下FutureTask的构造函数

    public FutureTask(Callable<V> callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }

    public FutureTask(Runnable runnable, V result) {
        this.callable = Executors.callable(runnable, result);
        this.state = NEW;       // ensure visibility of callable
    }

Runnable注入会被Executors.callable()函数转换为Callable类型,即FutureTask最终都是执行Callable类型的任务。

    public static <T> Callable<T> callable(Runnable task, T result) {
        if (task == null)
            throw new NullPointerException();
        return new RunnableAdapter<T>(task, result);
    }
    private static final class RunnableAdapter<T> implements Callable<T> {
        private final Runnable task;
        private final T result;
        RunnableAdapter(Runnable task, T result) {
            this.task = task;
            this.result = result;
        }
        public T call() {
            task.run();
            return result;
        }
        public String toString() {
            return super.toString() + "[Wrapped task = " + task + "]";
        }
    }

总结一下FutureTask
FutureTask是Future接口的一个唯一实现类。
FutureTask继承了Runnable,因此它既可以通过Thread包装来直接执行,也可以提交给ExecutorService来执行。
FutureTask实现了Future,可以直接通过get()函数获取执行结果,该函数会阻塞,直到结果返回。

2.3 二者对比

  • 接口类型
    Future 是一个接口,用于表示一个异步计算的结果,可以通过它来获取任务的执行状态和结果。
    FutureTask 是一个实现了 Future 接口的具体类,同时也实现了 Runnable 接口,可以作为一个可执行的任务提交给 ExecutorService 执行。
  • 功能
    Future 接口主要用于获取异步任务的执行状态和结果,可以取消任务、检查任务是否完成,并获取任务的返回结果。
    FutureTask 类是一个可执行的任务,可以被提交给 ExecutorService 执行,并且可以通过 Future 接口来获取任务的执行状态和结果。
  • 用法
    Future 通常用于提交 Callable 任务后返回一个 Future 对象,通过该对象可以获取任务的执行状态和结果。
    FutureTask 可以直接作为一个任务提交给 ExecutorService,也可以手动创建并执行。FutureTask 可以包装 Callable 或 Runnable 任务,并提供更多的控制和状态查询功能。
  • 状态管理
    Future 接口提供了一种轻量级的异步计算结果的管理机制,但无法手动触发任务的执行。
    FutureTask 类提供了更多的状态管理功能,可以手动触发任务的执行、取消任务的执行,并且可以获取任务的执行状态和结果。

总的来说,Future 接口是用于管理异步任务的结果和状态的轻量级接口,而 FutureTask 类是一个具体的实现类,提供了更多的功能和灵活性,可以作为一个可执行的任务提交给 ExecutorService 执行。


三、综合使用

3.1 Callable执行+Future获取结果

 public static void test1() {
        ExecutorService executor = Executors.newSingleThreadExecutor();

        Callable<Integer> task = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                // 模拟一个耗时的计算任务
                Thread.sleep(2000);
                return 42;
            }
        };

        Future<Integer> future = executor.submit(task);

        System.out.println("Task submitted");

        try {
            // 获取任务的执行结果,会阻塞当前线程直到任务完成
            int result = future.get();
            System.out.println("Task result: " + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        executor.shutdown();
    }

在这里插入图片描述

3.2 Callable执行任务+FutureTask获取执行结果

 public static void test2() {
        Callable<Integer> task = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                // 模拟一个耗时的计算任务
                Thread.sleep(2000);
                return 42;
            }
        };

        FutureTask<Integer> futureTask = new FutureTask<>(task);

        Thread thread = new Thread(futureTask);
        thread.start();

        System.out.println("Task submitted");

        try {
            // 获取任务的执行结果,会阻塞当前线程直到任务完成
            int result = futureTask.get();
            System.out.println("Task result: " + result);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }

在这里插入图片描述

四、应用场景

讲了半天,了解一下它的应用场景吧

  • 异步任务执行:FutureTask 可以用来执行异步任务,通过 Callable 接口创建任务并提交给 FutureTask,在需要的时候获取任务的执行结果。
  • 并发任务控制:FutureTask 可以用来控制多个并发任务的执行顺序和结果获取。可以通过多个 FutureTask 对象来管理多个任务,实现任务的并发执行和结果的收集。
  • 超时处理:Future 接口提供了 get 方法的重载版本,可以传入超时时间,用于控制任务的执行时间,避免任务执行时间过长导致程序阻塞。
  • 结果缓存:可以将任务的执行结果缓存起来,避免重复执行相同的任务。FutureTask 可以用来缓存任务的执行结果,当需要结果时先检查缓存,如果缓存中有结果则直接返回,否则执行任务并缓存结果。
  • 多线程协作:FutureTask 可以用来实现多个线程之间的协作。一个线程执行任务,另一个线程等待获取任务执行结果,通过 FutureTask 可以很方便地实现线程之间的通信和协作。

在这里插入图片描述

  • 37
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值