Guava ---- Concurrent并发
Guava在JDK1.5的基础上, 对并发包进行扩展。 有一些是易用性的扩展(如Monitor)。 有一些是功能的完好(如ListenableFuture)。 再加上一些函数式编程的特性, 使并发包的灵活性极大的提高...
Monitor的使用:
import com.google.common.util.concurrent.Monitor; import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean; /**
* Monitor类语义和 synchronized 或者 ReentrantLocks是一样的, 仅仅同意一个线程进入
*/
public class MonitorSample { private static final int MAX_SIZE = 3; private Monitor monitor = new Monitor(); private List<String> list = new ArrayList<String>(); Monitor.Guard listBelowCapacity = new
Monitor.Guard(monitor) {
@Override
public boolean isSatisfied() {
return list.size() < MAX_SIZE;
}
}; public void addToList(String item) throws InterruptedException {
// 超过MAX_SIZE, 会锁死
//monitor.enterWhen(listBelowCapacity); // 超过返回false 不会锁死
Boolean a = monitor.tryEnterIf(listBelowCapacity);
try {
list.add(item);
} finally { // 确保线程会推出Monitor锁
monitor.leave();
}
} public static void main(String[] args) {
MonitorSample monitorSample = new MonitorSample();
for (int count = 0; count < 5; count++) {
try {
monitorSample.addToList(count + "");
}
catch (Exception e) {
System.out.println(e);
}
} Iterator iteratorStringList = monitorSample.list.iterator();
while (iteratorStringList.hasNext()) {
System.out.println(iteratorStringList.next());
}
} }
Future的扩展: 可识别的返回结果。 可改变的返回结果
package com.wenniuwuren.listenablefuture; import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future; import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors; /**
* 在使用ListenableFuture前, 最好看下JDK的Future使用
*
* @author wenniuwuren
*
*/
public class ListenableFutureTest {
public static void main(String[] args) { // Guava封装后带有执行结束监听任务执行结束的功能
ExecutorService executorService =
MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(5)); ListenableFuture<String> listenableFuture = (ListenableFuture<String>) executorService
.submit(new Callable<String>() {
public String call() throws Exception {
return "task success ";
}
}); /* Futrue初始版本号 // JDK 自带线程池
//ExecutorService executor = Executors.newCachedThreadPool(); // JDK Future
Future<Integer> future = executor.submit(new Callable<Integer>() {
public Integer call() throws Exception {
return 1;
}
}); // JDK Future真正获取结果的地方
try {
Integer count = future.get();
} catch (Exception e) {
e.printStackTrace();
}*/ /* listenableFuture 结束监听版本号
// 相比JDK的Future等待结果, Guava採用监听器在任务完毕时调用
// 可是有个缺陷, 对最后完毕的结果没法对操作成功/失败进行处理, 即run方法没返回值
listenableFuture.addListener(new Runnable() {
@Override
public void run() {
System.out.println("执行完毕");
}
}, executorService);*/ // 执行成功。将会返回 "task success successfully" 攻克了listenableFuture 结束监听版本号不能对结果进行操作问题
FutureCallbackImpl callback = new FutureCallbackImpl();
// 和计算结果同步执行
//Futures.addCallback(listenableFuture, callback); //假设计算较大, 结果的訪问使用异步 将会使用executorService线程去异步执行
Futures.addCallback(listenableFuture, callback, executorService); System.out.println(callback.getCallbackResult()); } } class FutureCallbackImpl implements FutureCallback<String> {
private StringBuilder builder = new StringBuilder(); @Override
public void onSuccess(String result) {
builder.append(result).append("successfully");
} @Override
public void onFailure(Throwable t) {
builder.append(t.toString());
} public String getCallbackResult() {
return builder.toString();
}
}
Guava ---- Concurrent并发的更多相关文章
- Erlang Concurrent 并发进阶
写在前面的话 本文来源于官方教程 Erlang -- Concurrent Programming.虽然没有逻辑上的关系,但建议在掌握了Erlang入门系列教程的一些前置知识后继续阅读. 之前我是逐小 ...
- java concurrent 并发多线程
Concurrent 包结构 ■ Concurrent 包整体类图 ■ Concurrent包实现机制 综述: 在整个并发包设计上,Doug Lea大师采用了3.1 Concurrent包整体架构的三 ...
- [Java Concurrent] 并发访问共享资源的简单案例
EvenGenerator 是一个偶数生成器,每调用一个 next() 就会加 2 并返回叠加后结果.在本案例中,充当被共享的资源. EvenChecker 实现了 Runnable 接口,可以启动新 ...
- java Concurrent并发容器类 小结
Java1.5提供了多种并发容器类来改进同步容器的性能. 同步容器将所有对容器的访问都串行化,以实现他们的线程安全性.这种方法的代价是严重降低并发性,当多个线程竞争容器的锁时,吞吐量将严重减低. 一 ...
- Concurrent - 并发框架
原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/11426833.html SynchronizedMap和ConcurrentHashMap有什么区别? ...
- 读Cassandra源码之并发
java 并发与线程池 java并发包使用Executor框架来进行线程的管理,Executor将任务的提交与执行过程分开,直接使用Runnable表示任务.future获取返回值.ExecutorS ...
- 有关google的guava工具包详细说明
Guava 中文是石榴的意思,该项目是 Google 的一个开源项目,包含许多 Google 核心的 Java 常用库. 目前主要包含: com.google.common.annotations c ...
- (翻译)Google Guava Cache
翻译自Google Guava Cache This Post is a continuation of my series on Google Guava, this time covering G ...
- Google Guava入门(一)
Guava作为Java编程的助手,可以提升开发效率,对Guava设计思想的学习则极大的有益于今后的编程之路.故在此对<Getting Started with Google Guava>一 ...
随机推荐
- SoapUI对于Json数据进行属性值获取与传递
SoapUI的Property Transfer功能可以很好地对接口请求返回的数据进行参数属性获取与传递,但对于Json数据,SoapUI会把数据格式先转换成XML格式,但实际情况却是,转换后的XML ...
- 任务备忘(已经完成):用python写一个格式化xml字符串的程序
功能: 1.将xml中多余的空格,换行符去掉,让xml字符串变成一行. 2.将xml中添加缩进,使用print能正确打印添加缩进后的字符串. 思路: 采用正则表达式来判断xml中字符串的类型: 1.文 ...
- POJ-3278 抓住这头牛
广搜解决. 广搜搜出最短路,直接输出返回就行了. 每个点只搜一次,而且界限进行一次判断. else 语句里面不要用if else if,这样的话就直走一条路了. #include <ios ...
- SVN 初级教程
版本控制器:SVN 1.SVN 作用? 备份.代码还原.协同修改.多版本项目文件管理.追溯问题代码的编写人和编写时间.权限控制等. 2.版本控制简介 2.1 版本控制[Revision control ...
- VMware Workstation 14 UEFI启动
1.新建虚拟机 完成后不要启动 修改虚拟机目录下的XXX.vmx文件 添加一行:firmware="efi" 然后启动UEFI安装系统.
- 【HIHOCODER 1325】 平衡树·Treap
描述 小Ho:小Hi,我发现我们以前讲过的两个数据结构特别相似. 小Hi:你说的是哪两个啊? 小Ho:就是二叉排序树和堆啊,你看这两种数据结构都是构造了一个二叉树,一个节点有一个父亲和两个儿子. 如果 ...
- Fiddler抓包-只抓APP的请求
from:https://www.cnblogs.com/yoyoketang/p/6582437.html fiddler抓手机app的请求,估计大部分都会,但是如何只抓来自app的请求呢? 把来自 ...
- Dream City(线性DP)
描述 JAVAMAN is visiting Dream City and he sees a yard of gold coin trees. There are n trees in the ya ...
- VMware搭建Oracle 11g RAC测试环境 For Linux
环境如下: Linux操作系统:Centos 6.5 64bit (这个版本的redhat 6内核等OS在安装grid最后执行root.sh时会出现crs-4124,是oracle11.2.0.1的b ...
- 【并查集】F.find the most comfortable road
https://www.bnuoj.com/v3/contest_show.php?cid=9146#problem/F [题意] 给定n个城市和m条带权边,q次查询,问某两个城市之间的所有路径中最大 ...