您的位置:首页 > 编程语言 > Java开发

Java并发编程类学习二(线程的包装)

2015-12-25 17:18 260 查看

线程的包装

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

Future

表示异步计算处理后的结果。可以检查计算是否完成,是否可以取消。get()方法将一直阻塞等到计算的完成才返回结果。

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


FutureTask

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

FutureTask 可以包装Callable和Runnable 。

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

public class FutureTask<V> implements RunnableFuture<V>


而RunnableFuture继承了Runnable和Future

public interface RunnableFuture<V> extends Runnable, Future<V> {
/**
* Sets this Future to the result of its computation
* unless it has been cancelled.
*/
void run();
}


示例代码

这里借用《Java并发编程实战》中缓存计算器的例子。例子要求把计算的结果缓存下来,如果下次还有还有相同的计算请求,则直接返回缓存的计算结果,否则开始计算,把计算结果加入缓存中。

计算接口:

public interface Computable<A, V> {
V compute(A arg) throws ExecutionException;
}


实现:

public class CacheComputable<A, V> implements Computable<A, V> {
private final Map<A, Future<V>> cache = new ConcurrentHashMap<>();
private final Computable<A, V> c;
public CacheComputable(Computable<A, V> c) {
this.c = c;
}

@Override
public V compute(final A arg) throws ExecutionException {
Future<V> f = cache.get(arg);
Callable<V> eval = new Callable<V>(){
@Override
public V call() throws Exception {
return c.compute(arg);
}

};

if (f == null){
FutureTask<V> 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());
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 并发编程