美文网首页
Java的Callable、Future、FutureTask

Java的Callable、Future、FutureTask

作者: 渐进逾 | 来源:发表于2020-04-05 00:03 被阅读0次

    1.Callable

    Callable用来执行任务,产生结果,而Future用来获得结果。
    在开发多线程应用程序的传统方式中,我们创建线程并为其提供Runnable任务。Callable与Runnable非常相似,它有一个细微的区别,它可以返回结果或抛出异常,而Runnable的run方法的返回类型为void。

    Callable位于java.util.concurrent包下,它也是一个接口,在它里面也只声明了一个方法,只不过这个方法叫做call():

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // this can neither return the result nor throw an exception
        }
    }
    

    但是,Callable可以返回任务的结果并且可以抛出异常。您也可以指定结果类型。为简单起见,我把它作为String,但只要call()方法返回它,它就可以是任何复杂的对象。

    
    Callable<String> callable = new Callable<String>() {
        @Override
        public String call() throws Exception {
            return "this can return output OR can throw Exception";
        }
    };
    

    既然您有Callable或任务,您需要能够运行该任务以获得输出。您可以使用ExecutorService使用它的submit()方法运行任务,或使用invokeAll()运行多个任务 ,您可以在其中提交可调用任务的集合。

    现在是有趣的部分,submit()的返回类型是Future <T>,其中T是输出(String,如上例所示),invokeAll()的返回类型是List <Future <T >>

    Future表示异步计算的结果。Java提供了检查计算是否完成,等待它完成或从中检索结果的方法。(它非常类似于javascript承诺,如果这使它易于理解)。因此,为了获得未来的结果,我们只需要调用get()就可以了。

    ExecutorService executorService = Executors.newFixedThreadPool(10);
    // callable from above code
    Future<String> future = executorService.submit(callable);
    String output = future.get();
    

    完整代码:

    public class HealthCheckService {
    
      private HttpHandler httpHandler;
      private Config config;
      private ExecutorService executor;
    
      public HealthCheckService(HttpHandler httpHandler,Config config) {
        this.httpHandler = httpHandler;
        this.configuration = configuration;
        int size = config.servers.size();
        this.executor = Executors.newFixedThreadPool(size);
      }
    
      public List<HealthCheckResult> getHealthCheck() throws Exception {
        List<Callable<HealthCheck>> tasks = prepareTasks(config.uri);
        List<Future<HealthCheck>> futures = executor.invokeAll(tasks);
        List<HealthCheck> output = new ArrayList<>();
        for (Future<HealthCheckResult> future: futures) {
          output.add(future.get());
        }
        return output;
      }
    
      private List<Callable<HealthCheck>> prepareTasks(String api) {
        List<Callable<HealthCheckResult>> tasks = new ArrayList();
          for (String server: config.servers) {
            tasks.add(() -> httpHandler.getStatus(api));
          }
          return tasks;
      }
    }
    

    2.Future

    Future常用方法——
    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;
    }
    

    ①V get() :获取异步执行的结果,如果没有结果可用,此方法会阻塞直到异步计算完成。

    ②V get(Long timeout , TimeUnit unit) :获取异步执行结果,如果没有结果可用,此方法会阻塞,但是会有时间限制,如果阻塞时间超过设定的timeout时间,该方法将抛出异常。

    ③boolean isDone() :如果任务执行结束,无论是正常结束或是中途取消还是发生异常,都返回true。

    ④boolean isCanceller() :如果任务完成前被取消,则返回true。

    ⑤boolean cancel(boolean mayInterruptRunning) :如果任务还没开始,执行cancel(...)方法将返回false;如果任务已经启动,执行cancel(true)方法将以中断执行此任务线程的方式来试图停止任务,如果停止成功,返回true;当任务已经启动,执行cancel(false)方法将不会对正在执行的任务线程产生影响(让线程正常执行到完成),此时返回false;当任务已经完成,执行cancel(...)方法将返回false。mayInterruptRunning参数表示是否中断执行中的线程。

    通过方法分析我们也知道实际上Future提供了3种功能:

    (1)能够中断执行中的任务
    (2)判断任务是否执行完成
    (3)获取任务执行完成后额结果。

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

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

    3.FutureTask

    FutureTask的实现:

    public class FutureTask<V> implements RunnableFuture<V>
    

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

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

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

    FutureTask提供了2个构造器:

    public FutureTask(Callable<V> callable) {
    }
    public FutureTask(Runnable runnable, V result) {
    }
    

    事实上,FutureTask是Future接口的一个唯一实现类。

    相关文章

      网友评论

          本文标题:Java的Callable、Future、FutureTask

          本文链接:https://www.haomeiwen.com/subject/yzpephtx.html