让开发效率爆表的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(); } }
文章来自:http://blog.csdn.net/wenniuwuren/article/details/46421121