博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java并发编程类学习二(线程的包装)
阅读量:2491 次
发布时间:2019-05-11

本文共 1782 字,大约阅读时间需要 5 分钟。

线程的包装

可以用这些类对线程进行包装,获取线程的运行的状态。

Future

表示异步计算处理后的结果。可以检查计算是否完成,是否可以取消。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; }

FutureTask

可取消的异步任务。主要实现了Future接口的功能。方法中包括开始和取消任务,查询任务是否结束,检索任务执行后的结果。

FutureTask 可以包装Callable和Runnable 。

FutureTask 定义如下,实现了RunnableFuture接口

public class FutureTask
implements RunnableFuture

而RunnableFuture继承了Runnable和Future

public interface RunnableFuture
extends 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 { Future
f = 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/

你可能感兴趣的文章
Xcode 工程文件打开不出来, cannot be opened because the project file cannot be parsed.
查看>>
iOS在Xcode6中怎么创建OC category文件
查看>>
5、JavaWeb学习之基础篇—标签(自定义&JSTL)
查看>>
8、JavaWEB学习之基础篇—文件上传&下载
查看>>
reRender属性的使用
查看>>
href="javascript:void(0)"
查看>>
h:panelGrid、h:panelGroup标签学习
查看>>
f:facet标签 的用法
查看>>
<h:panelgroup>相当于span元素
查看>>
java中append()的方法
查看>>
必学高级SQL语句
查看>>
经典SQL语句大全
查看>>
log日志记录是什么
查看>>
<rich:modelPanel>标签的使用
查看>>
<h:commandLink>和<h:inputLink>的区别
查看>>
<a4j:keeyAlive>的英文介绍
查看>>
关于list对象的转化问题
查看>>
VOPO对象介绍
查看>>
suse创建的虚拟机,修改ip地址
查看>>
linux的挂载的问题,重启后就挂载就没有了
查看>>