学习Callable和Future笔记

    xiaoxiao2022-07-13  167

    Callable、Future和FutureTask

    创建线程的2种方式,一种是直接继承Thread,另外一种就是实现Runnable接口。 这2种方式都有一个缺陷就是:在执行完任务之后无法获取执行结果。 如果需要获取执行结果,就必须通过共享变量或者使用线程通信的方式来达到效果,这样使用起来就比较麻烦。 而自从Java 1.5开始,就提供了Callable和Future,通过它们可以在任务执行完毕之后得到任务执行结果。

    Callable和Runnable接口对比

    Runnable接口

    java.lang.Runnable吧,它是一个接口,在它里面只声明了一个run()方法,创建一个实现类实现它,把一些费时的操作写在里面,然后使用某个线程去执行该实现类。

    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(); }

    由于run()方法返回值为void类型,所以在执行完任务之后无法返回任何结果,无法抛出异常。

    Callable接口

    Callable位于java.util.concurrent包下,它也是一个接口,在它里面也只声明了一个方法,只不过这个方法叫做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; } 可以看到,这是一个泛型接口,call()函数返回的类型就是传递进来的V类型。 与Runnable对比,明显Callable功能更强大一些,被线程执行后,可以返回值,可以抛出异常,可以认为是有回调的Runnable。

    Callable的使用

    一般情况下是配合ExecutorService来使用的,在ExecutorService接口中声明了若干个submit方法的重载版本:

    <T> Future<T> submit(Callable<T> task); <T> Future<T> submit(Runnable task, T result); Future<?> submit(Runnable task);

    第一个submit方法里面的参数类型就是Callable。 下面是一个使用Callable的例子:

    import lombok.extern.slf4j.Slf4j; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; @Slf4j public class FutureExample { static class MyCallable implements Callable<String> { @Override public String call() throws Exception { log.info("do something in call"); Thread.sleep(5000); return "Done"; } } public static void main(String[] args) throws Exception { ExecutorService executorService = Executors.newCachedThreadPool(); Future<String> future = executorService.submit(new MyCallable()); log.info("do something in main"); Thread.sleep(1000); String result = future.get(); //会阻塞线程知道前面的代码执行完才执行后面的代码 log.info("result: {}",result); } }

    执行结果如下:

    17:59:20.162 [pool-1-thread-1] INFO com.mmall.concurrency.example.aqs.FutureExample - do something in call 17:59:20.162 [main] INFO com.mmall.concurrency.example.aqs.FutureExample - do something in main 17:59:25.165 [main] INFO com.mmall.concurrency.example.aqs.FutureExample - result: Done

    Future

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

    Future类位于java.util.concurrent包下,它是一个接口:

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

    在Future接口中声明了5个方法,下面依次解释每个方法的作用: cancel方法用来取消任务,如果取消任务成功则返回true,如果取消任务失败则返回false。参数mayInterruptIfRunning表示是否允许取消正在执行却没有执行完毕的任务,如果设置true,则表示可以取消正在执行过程中的任务。如果任务已经完成,则无论mayInterruptIfRunning为true还是false,此方法肯定返回false,即如果取消已经完成的任务会返回false;如果任务正在执行,若mayInterruptIfRunning设置为true,则返回true,若mayInterruptIfRunning设置为false,则返回false;如果任务还没有执行,则无论mayInterruptIfRunning为true还是false,肯定返回true。

    isCancelled方法表示任务是否被取消成功,如果在任务正常完成前被取消成功,则返回 true。

    isDone方法表示任务是否已经完成,若任务完成,则返回true;

    get()方法用来获取执行结果,这个方法会产生阻塞,会一直等到任务执行完毕才返回;

    get(long timeout, TimeUnit unit)用来获取执行结果,如果在指定时间内,还没获取到结果,就直接返回null并抛出TimeoutException。 也就是说Future提供了三种功能:   1)判断任务是否完成;

    2)能够中断任务;

    3)能够获取任务执行结果。

    因为Future只是一个接口,所以是无法直接用来创建对象使用的,因此就有了下面的FutureTask。

    FutureTask

    FutureTask实现了RunnableFuture接口,这个接口的定义如下:

    public interface RunnableFuture<V> extends Runnable, Future<V> { void run(); }

    可以看到这个接口继承了Runnable和Future接口,接口中的具体实现由FutureTask来实现。这个类的两个构造方法如下 :

    public FutureTask(Callable<V> callable) { if (callable == null) throw new NullPointerException(); sync = new Sync(callable); } public FutureTask(Runnable runnable, V result) { sync = new Sync(Executors.callable(runnable, result)); }

    如上提供了两个构造函数,一个以Callable为参数,另外一个以Runnable为参数。这些类之间的关联对于任务建模的办法非常灵活,允许你基于FutureTask的Runnable特性(因为它实现了Runnable接口),把任务写成Callable,然后封装进一个由执行者调度并在必要时可以取消的FutureTask。

    FutureTask可以由执行者调度,这一点很关键。它对外提供的方法基本上就是Future和Runnable接口的组合:get()、cancel、isDone()、isCancelled()和run(),而run()方法通常都是由执行者调用,我们基本上不需要直接调用它。

    FutureTask的两个例子

    1、对比上面Callable 的例子

    import lombok.extern.slf4j.Slf4j; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; @Slf4j public class FutureTaskExample { public static void main(String[] args) throws Exception { FutureTask<String> futureTask = new FutureTask<>(new Callable<String>() { @Override public String call() throws Exception { log.info("do something in call"); Thread.sleep(5000); return "Done"; } }); new Thread(futureTask).start(); log.info("do something in main"); Thread.sleep(1000); String result = futureTask.get(); log.info("result: {}",result); } }

    执行结果如下:

    18:17:37.806 [Thread-0] INFO com.mmall.concurrency.example.aqs.FutureTaskExample - do something in call 18:17:37.803 [main] INFO com.mmall.concurrency.example.aqs.FutureTaskExample - do something in main 18:17:42.809 [main] INFO com.mmall.concurrency.example.aqs.FutureTaskExample - result: Done

    2、借鉴的例子

    import java.util.concurrent.*; public class MyCallable implements Callable<String> { private long waitTime; public MyCallable(long waitTime) { this.waitTime = waitTime; } @Override public String call() throws Exception { Thread.sleep(waitTime); return Thread.currentThread().getName(); } public static void main(String[] args) { //要执行的任务 MyCallable myCallable1 = new MyCallable(1000); MyCallable myCallable2 = new MyCallable(3000); // 将Callable写的任务封装到一个由执行者调度的FutureTask对象 FutureTask<String> task1 = new FutureTask<String>(myCallable1); FutureTask<String> task2 = new FutureTask<String>(myCallable2); ExecutorService executorService = Executors.newFixedThreadPool(2); executorService.execute(task1); executorService.execute(task2); while (true) { if(task1.isDone() && task2.isDone()) { //两个任务都完成 System.out.println("Done"); executorService.shutdown(); return; } try { if (!task1.isDone()) { //task1未完成,会等到task1完成后执行get方法 System.out.println("task1 output=" + task1.get()); } System.out.println("Waiting for task2 to complete"); //用来获取执行结果,如果在指定时间内,还没获取到结果, //就直接返回null,并抛出超时异常 String s = task2.get(1000,TimeUnit.MILLISECONDS); if (s!=null) { System.out.println("task2 output =" + s); } } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } catch (TimeoutException e) { System.out.println("TimeoutException"); } } } }

    执行结果:

    task1 output=pool-1-thread-1 Waiting for task2 to complete TimeoutException //等待一秒内未获取到结果,捕获到异常 Waiting for task2 to complete task2 output =pool-1-thread-2 Done

    参考: [https://www.cnblogs.com/fengsehng/p/6048609.html]

    最新回复(0)