本文共 1782 字,大约阅读时间需要 5 分钟。
可以用这些类对线程进行包装,获取线程的运行的状态。
表示异步计算处理后的结果。可以检查计算是否完成,是否可以取消。get()方法将一直阻塞等到计算的完成才返回结果。
public interface Future{ boolean cancel(boolean mayInterruptIfRunning); boolean isCancelled(); boolean isDone(); V get() throws InterruptedException, ExecutionException; V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; }
可取消的异步任务。主要实现了Future接口的功能。方法中包括开始和取消任务,查询任务是否结束,检索任务执行后的结果。
FutureTask 可以包装Callable和Runnable 。FutureTask 定义如下,实现了RunnableFuture接口
public class FutureTaskimplements RunnableFuture
而RunnableFuture继承了Runnable和Future
public interface RunnableFutureextends Runnable, Future { /** * Sets this Future to the result of its computation * unless it has been cancelled. */ void run();}
这里借用《Java并发编程实战》中缓存计算器的例子。例子要求把计算的结果缓存下来,如果下次还有还有相同的计算请求,则直接返回缓存的计算结果,否则开始计算,把计算结果加入缓存中。
计算接口:
public interface Computable { V compute(A arg) throws ExecutionException;}
实现:
public class CacheComputable implements Computable { private final Map > cache = new ConcurrentHashMap<>(); private final Computable c; public CacheComputable(Computable c) { this.c = c; } @Override public V compute(final A arg) throws ExecutionException { Futuref = cache.get(arg); Callable eval = new Callable (){ @Override public V call() throws Exception { return c.compute(arg); } }; if (f == null){ FutureTask ft = new FutureTask<>(eval); f = ft; cache.put(arg, f); ft.run();//开始调用c.compute } try { return f.get(); } catch (InterruptedException e) { e.printStackTrace(); throw new ExecutionException(e.getCause()); } }}
转载地址:http://pxhrb.baihongyu.com/