本文已参加「新人创作礼」活动,一起敞开创作之路。

Future就是对于详细的Runnable或者Callable使命的履行成果进行撤销、查询是否完结、获取成果等操作。必要时能够经过get办法获取履行成果,该办法会阻塞直到使命回来成果。
Future类位于java.util.concurrent包下,它是一个接口:

/**
* @see FutureTask 
 * @see Executor 
 * @since 1.5 
 * @author Doug Lea 
 * @param <V> The result type returned by this Future's <tt>get</tt> method 
 */  
public interface Future<V> {  
    /** 
     * Attempts to cancel execution of this task.  This attempt will 
     * fail if the task has already completed, has already been cancelled, 
     * or could not be cancelled for some other reason. If successful, 
     * and this task has not started when <tt>cancel</tt> is called, 
     * this task should never run.  If the task has already started, 
     * then the <tt>mayInterruptIfRunning</tt> parameter determines 
     * whether the thread executing this task should be interrupted in 
     * an attempt to stop the task.     * 
     */  
    boolean cancel(boolean mayInterruptIfRunning);  
    /** 
     * Returns <tt>true</tt> if this task was cancelled before it completed 
     * normally. 
     */  
    boolean isCancelled();  
    /** 
     * Returns <tt>true</tt> if this task completed. 
     * 
     */  
    boolean isDone();  
    /** 
     * Waits if necessary for the computation to complete, and then 
     * retrieves its result. 
     * 
     * @return the computed result 
     */  
    V get() throws InterruptedException, ExecutionException;  
    /** 
     * Waits if necessary for at most the given time for the computation 
     * to complete, and then retrieves its result, if available. 
     * 
     * @param timeout the maximum time to wait 
     * @param unit the time unit of the timeout argument 
     * @return the computed result 
     */  
    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。
也就是说Future提供了三种功能:

1)判断使命是否完结;
2)能够中止使命;
3)能够获取使命履行成果。
由于Future仅仅一个接口,所以是无法直接用来创建对象运用的,因而就有了下面的FutureTask。

FutureTask

FutureTask的完成:

public class FutureTask<V> implements RunnableFuture<V>

FutureTask类完成了RunnableFuture接口,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接口,而FutureTask完成了RunnableFuture接口。所以它既能够作为Runnable被线程履行,又能够作为Future得到Callable的回来值。
FutureTask提供了2个构造器:

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

RunnableAdapter适配器

/**
 * A callable that runs given task and returns given result 
 */  
static final class RunnableAdapter<T> implements Callable<T> {  
    final Runnable task;  
    final T result;  
    RunnableAdapter(Runnable task, T result) {  
        this.task = task;  
        this.result = result;  
    }  
    public T call() {  
        task.run();  
        return result;  
    }  
}  

FutureTask是Future接口的一个仅有完成类。
FutureTask完成了Runnable,因而它既能够经过Thread包装来直接履行,也能够提交给ExecuteService来履行。
FutureTask完成了Futrue能够直接经过get()函数获取履行成果,该函数会阻塞,直到成果回来。

实例:
Callable+Future获取履行成果

public class Test {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newCachedThreadPool();
        Task task = new Task();
        Future<Integer> result = executor.submit(task);
        executor.shutdown();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        System.out.println("主线程在履行使命");
        try {
            System.out.println("task运转成果"+result.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println("一切使命履行结束");
    }
}
class Task implements Callable<Integer>{
    @Override
    public Integer call() throws Exception {
        System.out.println("子线程在进行核算");
        Thread.sleep(3000);
        int sum = 0;
        for(int i=0;i<100;i++)
            sum += i;
        return sum;
    }
}

履行成果:

子线程在进行核算
主线程在履行使命
task运转成果4950
一切使命履行结束

Callable+FutureTask获取履行成果

public class Test {
    public static void main(String[] args) {
        //第一种方法
        ExecutorService executor = Executors.newCachedThreadPool();
        Task task = new Task();
        FutureTask<Integer> futureTask = new FutureTask<Integer>(task);
        executor.submit(futureTask);
        executor.shutdown();
        //第二种方法,注意这种方法和第一种方法效果是类似的,只不过一个运用的是ExecutorService,一个运用的是Thread
        /*Task task = new Task();
        FutureTask<Integer> futureTask = new FutureTask<Integer>(task);
        Thread thread = new Thread(futureTask);
        thread.start();*/
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        System.out.println("主线程在履行使命");
        try {
            System.out.println("task运转成果"+futureTask.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println("一切使命履行结束");
    }
}
class Task implements Callable<Integer>{
    @Override
    public Integer call() throws Exception {
        System.out.println("子线程在进行核算");
        Thread.sleep(3000);
        int sum = 0;
        for(int i=0;i<100;i++)
            sum += i;
        return sum;
    }
}