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. 最短路 || POJ 1797 Heavy Transportation

    Background Hugo Heavy is happy. After the breakdown of the Cargolifter project he can now expand bus ...

  2. Vickers Vane Pump - Hydraulic Vane Pump Failure: Cavitation, Mechanical Damage

    One of our readers recently wrote to me about the following questions: “Recently, we purchased a sec ...

  3. Linux配置ssh免密登录

    假定有3台机,用户名和IP分别是:C1  192.168.1.101C2  192.168.1.102C3  192.168.1.103 # 登入root用户su # 安装vimapt-get ins ...

  4. Xcode导入第三方库图文

    Three20这个与facebook亲戚的开源库是蜚声iPhone开发界,很多App都有它的影子,主要是其真得是功能强大.那么如何将Three20库添加到自己的项目中应用呢?一种是Python命令方式 ...

  5. SMTP error 554 !!

    哇,我真的amazing, incredible!! 我只是想写一个简单的邮件,结果他一直报554错误!!! 期间,通过百度,我发现了可能导致 此,讨厌至极的错误,有N多原因: 但我的原因 谜之离谱! ...

  6. 详解Spring面向切面编程(AOP)三种实现

    一.什么是AOP AOP(Aspect Oriented Programming),即面向切面编程,可以说是OOP(Object Oriented Programming,面向对象编程)的补充和完善. ...

  7. mysql主从同步 change master to配置

    CHANGE MASTER TO MASTER_HOST='10.0.0.52', MASTER_PORT=3308, MASTER_AUTO_POSITION=1, MASTER_USER='rep ...

  8. VMware搭建内网并通过iptables端口转发联网

    整体流程图 配置Server1 新建两块网卡 一块网卡设置为桥接模式,另外一块设置为仅主机模式 查看两块网卡配置 root@ubuntu:~# ifconfig ens33 Link encap:Et ...

  9. iframe的操作switch_to_frame使用方法.

    一.frame和iframe区别 Frame与Iframe两者可以实现的功能基本相同,不过Iframe比Frame具有更多的灵活性. frame是整个页面的框架,iframe是内嵌的网页元素,也可以说 ...

  10. cf839c Journey

    大水题 #include <iostream> #include <cstdio> using namespace std; int n, du[100005], hea[10 ...