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>一 ...
随机推荐
- centOS7安装 mysql-community-release-el7-5.noarch.rpm 包
一.rpm包 1.wget http://repo.mysql.com/mysql-community-release-el7-5.noarch.rpm(下载rpm) 2.rpm -ivh mysql ...
- 简单DP内容
1. 最长上升子序列 [题目描述] 给定N个数,求这N个数的最长上升子序列的长度. [样例输入] 7 2 5 3 4 1 7 6 [样例输出] 4 第一种解法:时间复杂度O(n^2), 状态设计:DP ...
- Installing MySQL 5.7.23 on CentOS 7
Installing MySQL 5.7.23 on CentOS 7 1. 安装前检查 1.1 检查NUMA是否开启 NUMA为什么要咋MySQL中禁用? MySQL是单进程多线程架构数据库,当nu ...
- Go:获取命令行参数
一.Low B 方式 package main import ( "fmt" "os" ) func main() { fmt.Println("命令 ...
- xshell连接Linux(centos6.8)失败的解决方法
注意:本人使用的是Centos6.8版本. Centos7以上版本linux命令会又不一样的地方. 启动xshell终端进行连接服务器:使用命令:ssh + ip地址或是手动使用可视化操作窗口操作, ...
- 剑指Offer(书):从尾到头打印链表
题目:输入一个链表,按链表值从尾到头的顺序返回一个ArrayList. 分析:若不允许修改原链表的值,则可以使用栈来实现,也可以使用另外一个ArrayList做中转的数据. public ArrayL ...
- Centos 7安装Mysql5.7
1.下载(国内镜像,比搜狐的快一点):http://mirrors.ustc.edu.cn/mysql-ftp/Downloads/MySQL-5.7/mysql-5.7.22-linux-glibc ...
- 构造MaxTree
链接:https://www.nowcoder.com/questionTerminal/a502c7c3c65e41fdaf65eec9e0654dcb 来源:牛客网 [编程题]构造MaxTree ...
- python018 Python3 输入和输出
Python3 输入和输出在前面几个章节中,我们其实已经接触了 Python 的输入输出的功能.本章节我们将具体介绍 Python 的输入输出. 输出格式美化Python两种输出值的方式: 表达式语句 ...
- zoj 2932 The Seven Percent Solution
The Seven Percent Solution Time Limit: 2 Seconds Memory Limit: 65536 KB Uniform Resource Identi ...