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 Listlist = new ArrayList (); 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)); ListenableFuturelistenableFuture = (ListenableFuture ) executorService .submit(new Callable () { public String call() throws Exception { return "task success "; } }); /* Futrue初始版本号 // JDK 自带线程池 //ExecutorService executor = Executors.newCachedThreadPool(); // JDK Future Future future = executor.submit(new Callable () { 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 { 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(); }}