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并发的更多相关文章

  1. Erlang Concurrent 并发进阶

    写在前面的话 本文来源于官方教程 Erlang -- Concurrent Programming.虽然没有逻辑上的关系,但建议在掌握了Erlang入门系列教程的一些前置知识后继续阅读. 之前我是逐小 ...

  2. java concurrent 并发多线程

    Concurrent 包结构 ■ Concurrent 包整体类图 ■ Concurrent包实现机制 综述: 在整个并发包设计上,Doug Lea大师采用了3.1 Concurrent包整体架构的三 ...

  3. [Java Concurrent] 并发访问共享资源的简单案例

    EvenGenerator 是一个偶数生成器,每调用一个 next() 就会加 2 并返回叠加后结果.在本案例中,充当被共享的资源. EvenChecker 实现了 Runnable 接口,可以启动新 ...

  4. java Concurrent并发容器类 小结

    Java1.5提供了多种并发容器类来改进同步容器的性能. 同步容器将所有对容器的访问都串行化,以实现他们的线程安全性.这种方法的代价是严重降低并发性,当多个线程竞争容器的锁时,吞吐量将严重减低.  一 ...

  5. Concurrent - 并发框架

    原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/11426833.html SynchronizedMap和ConcurrentHashMap有什么区别? ...

  6. 读Cassandra源码之并发

    java 并发与线程池 java并发包使用Executor框架来进行线程的管理,Executor将任务的提交与执行过程分开,直接使用Runnable表示任务.future获取返回值.ExecutorS ...

  7. 有关google的guava工具包详细说明

    Guava 中文是石榴的意思,该项目是 Google 的一个开源项目,包含许多 Google 核心的 Java 常用库. 目前主要包含: com.google.common.annotations c ...

  8. (翻译)Google Guava Cache

    翻译自Google Guava Cache This Post is a continuation of my series on Google Guava, this time covering G ...

  9. Google Guava入门(一)

    Guava作为Java编程的助手,可以提升开发效率,对Guava设计思想的学习则极大的有益于今后的编程之路.故在此对<Getting Started with Google Guava>一 ...

随机推荐

  1. C ++ _多线程笔记

    #include<iostream>#include <thread>//创建线程需要添加的头文件 using namespace std;/*thread join(阻塞:主 ...

  2. Java之字符,字符串替换

    /** 4. 字符串的替换操作 1. String replace(char oldChar,char newChar) //将新字符替换旧字符 3. String replaceFirst(Stri ...

  3. MySQL字符集设定与查询

    一.字符集设定 MySQL数据库允许对服务器.数据库.数据表.数据列级别的字符集作出互不影响的设定. 1.对服务器字符集设定是通过配置文件中选项character-set-server 设置,如 ch ...

  4. 老男孩老师的博客地址 - 转自devops1992

    害怕他那天不让人看了,所以我就复制一份到我自己的博客里. http://www.bootcdn.cn/bootstrap/  bootstrap cdn在线地址 http://www.cnblogs. ...

  5. Django之学员管理二

    Django之学员管理二 学生表的一对多的增删改查 views.py def students(request): #select students.sid,students.name,classes ...

  6. 关于Python中包裹传参和解包裹的理解

    1.包裹传参 首先思考一个问题:为什么要有包裹传参?原因包括但不仅限于以下两点:①不确定参数的个数.②希望函数定义的更加松散灵活 包裹传参分两种:包裹位置传参和包裹关键字传参.先看包裹位置传参: 在这 ...

  7. LeetCode(25)Reverse Nodes in k-Group

    题目 Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. ...

  8. centos7.4下搭建JDK+Tomcat+Nginx+Mysql+redis+Mongodb+maven+Git+Jenkins

    先干两件大事!先干两件大事!先干两件大事! 1.关闭selinux [root@mycentos ~]# vi /etc/selinux/config SELINUX=disabled 2.关闭防火墙 ...

  9. 飞行路线(BZOJ 2763)

    题目描述 Alice和Bob现在要乘飞机旅行,他们选择了一家相对便宜的航空公司.该航空公司一共在n个城市设有业务,设这些城市分别标记为0到n-1,一共有m种航线,每种航线连接两个城市,并且航线有一定的 ...

  10. 2016 Multi-University Training Contest 9 solutions BY 金策工业综合大学

    A Poor King Tag: Reversed BFS Preprocessing is needed to calculate answers for all positions (states ...