java 异步任务与结果

Callable, Future, FutureTask

Callable 与Runnable

Runnable 介绍

Runnable只是一个接口,它可以被任何类继承,它的实例通过线程执行

Callable 与Runnable区别
代码
public interface Runnable {

    public abstract void run();
}
作用:
  1. 当做线程使用
  2. 当做任务被线程执行。
特点
  1. 当做任务没有时run()方法没有返回值;
  2. 不能抛出异常;
Callable 介绍
源码
public interface Callable<V> {

    V call() throws Exception;
}

Callable是一个任务接口,它定义了一个带有返回值的并且抛出异常的任务。

作用
  1. 当做任务
特点
  1. 方法call() 具有返回值
  2. 可抛出异常,支持泛型

Future

future 介绍

future 代表异步操作运算的结果,它也是一个接口;
常用于获取运行结果,查询是否完成,对任务结果进行取消

public interface Future<V> {

    /**

       尝试取消当前任务,如果任务已经被完成,这个操作就失败返回fail,    
       参数 mayInterruptIfRunning 为ture 时,代表任务在执行中,也可以取消任务; 为false时,只能取消未被执行的任务。

     */
    boolean cancel(boolean mayInterruptIfRunning);

    /**
     * Returns {@code true} if this task was cancelled before it completed
     * normally.
     *
     * @return {@code true} if this task was cancelled before it completed
     */
    boolean isCancelled();

    /**
     返回任务是否完成。
     *
     * @return {@code true} if this task completed
     */
    boolean isDone();

    /**
     * 获取返回结果,有必要一直等在结果返回;
     */
    V get() throws InterruptedException, ExecutionException;

    /**
     * 获取执行结果,有必要就等待timeout , 指定时间内结果没有执行完,返回Null
     *
     * @param timeout the maximum time to wait
     * @param unit the time unit of the timeout argument
     * @return the computed result
     * @throws CancellationException if the computation was cancelled
     * @throws ExecutionException if the computation threw an
     * exception
     * @throws InterruptedException if the current thread was interrupted
     * while waiting
     * @throws TimeoutException if the wait timed out
     */
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}
功能
  1. 取消任务
  2. 获取任务执行结果
  3. 判断任务是否完成

FutureTask

简述

FutureTask 是一个类,

部分源码
public class FutureTask<V> implements RunnableFuture<V> {
.....

}
RunnableFuture
/**

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

RunnableFuture 继承了Runnable, 和Future,它既可以当做任务被执行,又可以判断结果是完成,但获取不到具体的值,因为它的父类是Callable 而不是Runnable。

FutureTask 是RunnableFuture 的子类实现。

示例

public class AsyncTask {

    public static void main(String args[]) throws InterruptedException, ExecutionException {

        ExecutorService service = Executors.newCachedThreadPool();
        MyTask1 task1 = new MyTask1();

        Future<String> result1 = service.submit(task1);
        System.out.println("...等待完成任务1。。执行结果是:" + result1.get());

        MyTask2 task2 = new MyTask2();
        Future<?> result2 = service.submit(task2);
        System.out.println("...等待完成任务2.。执行结果是。" + result2.get());

        FutureTask<String> ft = new FutureTask<String>(task1);

        Future<String> reuslt2 = (Future<String>) service.submit(ft);

        System.out.println("...等待任务3.。执行结果是:" + result2.get());

        service.shutdown();

    }


}

class MyTask2 implements Runnable {

    @Override
    public void run() {

        System.out.println("..执行Runnable任务。。");

    }

}


class MyTask1 implements Callable<String> {

    @Override
    public String call() throws Exception {
        System.out.println("...线程执行callable任务。");
        return "success";
    }

}
执行结果
...线程执行callable任务。
...等待完成任务1。。执行结果是:success
..执行Runnable任务。。
...等待完成任务2.。执行结果是。null
...等待任务3.。执行结果是:null
...线程执行callable任务。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章