Callable、FutureTask和Future详解带你理解java并发编程

一. Callable接口与Runnable接口区别

创建java线程,我们经常使用两种方式:

  • 一是直接继承Thread
  • 另一种是实现Runnable接口

但这两种方式有一个缺陷:在执行完任务之后无法直接获取执行结果。

1. 接口定义

1.1 Callable接口

public interface Callable<V> {
    V call() throws Exception;
}

1.2 Runnable接口

public interface Runnable {
    public abstract void run();
}

2. 区别

  • Runnable没有返回值;Callable可以返回执行结果(泛型)。
  • Runnable异常只能在内部处理,不能往上继续抛出;Callable接口的call()方法允许抛出异常。
  • Callable需要配合FutureTask或Future使用。

二. Future接口和FutureTask实现类

1. Future接口定义了5个方法

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

2. FutureTask实现了RunnableFuture接口,RunnableFuture继承了Runnable接口和Future接口

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

3. 基本用法举例

3.1 Runnable

Runnable runnable = new Runnable() {
    @Override
    public void run() {
        System.out.println("线程执行中...");
    }
};
Thread thread = new Thread(runnable);
thread.start();

3.2 Callable

3.2.1 FutureTask

Callable < Integer > callable = new Callable < Integer > () {
    @Override
    public Integer call() throws Exception {
        System.out.println("线程执行中...");
        return 100;
    }
};
FutureTask < Integer > futureTask = new FutureTask < Integer > (callable);
new Thread(futureTask).start();
// 等待1秒,让线程执行
TimeUnit.SECONDS.sleep(1);
if(futureTask.isDone()) {
    System.out.println("获取执行结果:" + futureTask.get());
}

3.2.2 Future

Callable < Integer > callable = new Callable < Integer > () {
    @Override
    public Integer call() throws Exception {
        System.out.println("线程执行中...");
        return 100;
    }
};
ExecutorService service = Executors.newCachedThreadPool();
Future < Integer > future = service.submit(callable);
// 等待1秒,让线程执行
TimeUnit.SECONDS.sleep(1);
if(futureTask.isDone()) {
    System.out.println("获取执行结果:" + future.get());
}

猜你喜欢

转载自blog.51cto.com/634435/2476201