Java终结任务:Callable和Future

在这里首先介绍下Callable和Future,咱们知道一般建立线程的2种方式,一种是直接继承Thread,另一种就是实现Runnable接口,可是这两种方式建立的线程不返回结果,而Callable是和Runnable相似的接口定义,可是经过实现Callable接口建立的线程能够有返回值,返回值类型能够任意定义。java

Callable接口

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类型。设计模式

那么怎么使用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通常是和ExecutorService配合来使用的,经过ExecutorService的实例submit获得Future对象。ide

Future

Future接口以下:函数

public interface Future<V> {
    boolean  cancel(boolean mayInterruptIfRunning);// 试图取消对此任务的执行
    boolean  isCancelled();      // 若是在任务正常完成前将其取消,则返回true
    boolean  isDone();           // 若是任务已完成(无论是正常仍是异常),则返回true
    V  get() throws InterruptedException, ExecutionException; // 方法用来获取执行结果,这个方法会产生阻塞,会一直等到任务执行完毕才返回;
    // 用来获取执行结果,若是在指定时间内,还没获取到结果,就直接返回null;
    V  get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
}

Future用于表示异步计算的结果。它的实现类是FutureTask。spa

若是不想分支线程阻塞主线程,又想取得分支线程的执行结果,就用FutureTask线程

FutureTask实现了RunnableFuture接口,这个接口的定义以下:设计

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

能够看出RunnableFuture继承了Runnable接口和Future接口,而FutureTask实现了RunnableFuture接口。因此它既能够做为Runnable被线程执行,又能够做为Future获得Callable的返回值。code

使用示例

package demo.future;
 
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
 
/**
 * 试验 Java 的 Future 用法
 */
public class FutureTest {
 
    public static class Task implements Callable<String> {
        @Override
        public String call() throws Exception {
            String tid = String.valueOf(Thread.currentThread().getId());
            System.out.printf("Thread#%s : in call\n", tid);
            return tid;
        }
    }
 
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        List<Future<String>> results = new ArrayList<Future<String>>();
        ExecutorService es = Executors.newCachedThreadPool();
        for(int i=0; i<100;i++)
            results.add(es.submit(new Task()));
 
        for(Future<String> res : results)
            System.out.println(res.get());
    }
 
}

终结任务

持有Future对象,能够调用cancel(),并所以可使用它来中断某个特定任务,若是将ture传递给cancel(),那么它就会拥有该线程上调用interrupt()以中止这个线程的权限。所以,cancel()是一种中断由Executor启动的单个线程的方式。对象

cancel()通常是搭配get()方法来使用的。比方说,有一种设计模式是设定特定的时间,而后去执行一个做业的线程,若是该做业可以在设定的时间内执行完毕,则直接返回结果,若是不能执行完毕,则中断做业的执行,继续执行下一个做业,在这种模式下,使用Callable和Future来实现是一个很是好的解决方案。

相关文章
相关标签/搜索