Java 多线程之 Future 接口

it2022-05-21  74

简介

FutureTask是Future接口的实现。Future 代表了异步计算的结果(the result of an asynchronous computation),并提供相应的方法以检查计算是否完整或者是否等待等操作。 结果只能在计算完成时使用方法get检索,如果必要则阻塞直到准备就绪。 取消由取消方法执行。 提供了其他方法来确定任务是否正常完成或被取消。 一旦计算完成,计算就无法取消。我们还可以声明Future <?>的形式和返回null作为底层任务的结果。

接口定义

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

主要方法说明

boolean cancel(boolean mayInterruptIfRunning); 取消现在执行的任务的执行,执行有三种情况: 情况1:若此任务已经执行结束、已经被取消或不能被取消,则会执行失败并返回false;情况2:若此任务还没有开始执行,那么子任务会被取消,不会再被执行;情况3:若此任务已经开始执行了,但是还没有执行结束,根据mayInterruptIfRunning的值有两种情况: 若 mayInterruptIfRunning 为 true,那么会中断执行任务的线程,然后返回true;若 mayInterruptIfRunning 为 false,会返回true,不会中断执行任务的线程。 boolean isCancelled() 判断此任务是否被取消。 若任务执行结束前调用了cancel(),则 cancel() 返回true,isCancelled() 返回 true;若任务执行结束前没有调用 cancel(),则返回 false;注:正常执行结束和发生异常结束,都算执行结束; boolean isDone() 判断任务是否完成。正常结束、发生异常结束或被取消,都属于结束并返回true;其他情况返回false。V get() 获取计算结果,结果的数据类型为V。这个方法会使调用线程会进入阻塞状态。调用有以下几种结果: 若计算任务已被取消,调用get()会抛出CancellationException;若计算过程中抛出异常,该方法会抛出ExecutionException;若当前线程在阻塞等待的时候被中断了,该方法会抛出InterruptedException。 V get(long timeout, TimeUnit unit) 带超时限制的get()。可以设置超时的时间,使用timeout表示值,unit表示单位(如秒,分钟)。如果在超时时间到了后仍然未完成计算,则会结束等待并抛出TimeoutException。

附:来自官方的示例

java.util.concurrent.Future<Integer> interface ArchiveSearcher { String search(String target); } class App { ExecutorService executor = ... ArchiveSearcher searcher = ... void showSearch(final String target) throws InterruptedException { Future future = executor.submit(new Callable() { public String call() { return searcher.search(target); }}); displayOtherThings(); // do other things while searching try { displayText(future.get()); // use future } catch (ExecutionException ex) { cleanup(); return; } } }} The FutureTask class is an implementation of Future thatimplements Runnable, and so may be executed by an Executor.For example, the above construction with submit could be replaced by: FutureTask<String> future = new FutureTask<String>(new Callable<String>() { public String call() { return searcher.search(target); }}); executor.execute(future);}

最新回复(0)