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>一 ...
随机推荐
- vs2010的资源视图中,对话框显示数字的解决方法之一
以上是不正常显示. 我这次遇到该问题的原因是资源名IDD_DLG_INTENSITY重复定义导致的, 所以在resource.h文件中去除重复定义就好了. 正常应该显示DD_XXX,如下图所示
- 最短路 || POJ 1847 Tram
POJ 1847 最短路 每个点都有初始指向,问从起点到终点最少要改变多少次点的指向 *初始指向的那条边长度为0,其他的长度为1,表示要改变一次指向,然后最短路 =========高亮!!!===== ...
- python爬虫---实现项目(一) Requests爬取HTML信息
上面的博客把基本的HTML解析库已经说完了,这次我们来给予几个实战的项目. 这次主要用Requests库+正则表达式来解析HTML. 项目一:爬取猫眼电影TOP100信息 代码地址:https://g ...
- Linux常用命令大全2
Linux命令是对Linux系统进行管理的命令.对于Linux系统来说,无论是中央处理器.内存.驱动.键盘.鼠标,还是用户等都是文件,Linux命令是它正常运行的核心.接下来,就来看看xp系统下载编辑 ...
- AES/DES 可逆性加密算法 -- java工具类
package com.lock.demo.service; import org.apache.tomcat.util.codec.binary.Base64; import javax.crypt ...
- python 04 学生信息管理系统
今天任务不多,做了学生信息管理系统1.0,使用字典存储学生个体信息,列表存储学生字典.注意dict定义要在循环体内,若定义成全局变量或循环体外,则旧数据会被新数据覆盖.dict属于可变类型数据,内容改 ...
- hdu1394(Minimum Inversion Number)线段树
明知道是线段树,却写不出来,搞了半天,戳,没办法,最后还是得去看题解(有待于提高啊啊),想做道题还是难啊. 还是先贴题吧 HDU-1394 Minimum Inversion Number Time ...
- 【HDU 6153】A Secret (KMP)
Problem Description Today is the birthday of SF,so VS gives two strings S1,S2 to SF as a present,whi ...
- Linux 命令大全 - 管理文件和目录的命令
1.pwd 显示当前目录 该命令的英文解释为print working directory(打印工作目录).输入pwd命令,Linux会输出当前目录. 2.cd 命令用来改变所在目录 cd / 转到根 ...
- python接口自动化-有token的接口项目使用unittest框架设计
获取token 在做接口自动化的时候,经常会遇到多个用例需要用同一个参数token,并且这些测试用例跨.py脚本了. 一般token只需要获取一次就行了,然后其它使用unittest框架的测试用例全部 ...