guava

  1. 最近花了点时间看了下com.google.guava里面的Guava的API,感觉有些确实比common有些工具好用,也简便。对于里面常用的工具做一个笔记方便以后自己查看(后面会继续)

  2. package cn.gov.zcy.admin;  
  3.   
  4. import com.google.common.base.Function;  
  5. import com.google.common.base.Optional;  
  6. import com.google.common.collect.*;  
  7. import com.google.common.primitives.Ints;  
  8. import com.sun.istack.internal.Nullable;  
  9. import org.joda.time.format.DateTimeFormat;  
  10. import org.joda.time.format.DateTimeFormatter;  
  11.   
  12. import java.util.*;  
  13.   
  14. import static com.google.common.base.Preconditions.*;  
  15. import static jdk.nashorn.internal.objects.NativeMath.log;  
  16.   
  17. /** 
  18.  * Created by shiwenxue on 16/7/13. 
  19.  */  
  20. public class GuavaTest {  
  21.     private static final DateTimeFormatter DATE_TIME_FORMAT = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");  
  22.   
  23.     /** 
  24.      * Optional傻瓜式防护类 
  25.      */  
  26.     public void optionalTest() {  
  27.   
  28.         // 创建指定引用的Optional实例,若引用为null则快速失败  
  29.         Optional<Integer> possible1 = Optional.of(5);  
  30.   
  31.         // 创建指定引用的Optional实例,若引用为null则表示缺失  
  32.         Optional<Integer> possible = Optional.fromNullable(5);  
  33.   
  34.         // 判断引用是否缺失  
  35.         boolean present = possible.isPresent();  
  36.   
  37.         // 返回Optional所包含的引用,若引用缺失,则抛出java.lang.IllegalStateException  
  38.         Integer num3 = possible.get();  
  39.   
  40.         // or:若引用缺失,返回or(T)中的T,否则返回引用对象  
  41.         Integer num2 = possible.or(6);  
  42.   
  43.         // orNull:若引用缺失,返回or(T)中的T,否则返回引用对象  
  44.         Integer num = possible.orNull();  
  45.   
  46.         // 返回Optional所包含引用的单例不可变集,如果引用存在,返回一个只有单一元素的集合,如果引用缺失,返回一个空集合。  
  47.         Set<Integer> set = possible.asSet();  
  48.   
  49.         System.out.println(set.size());  
  50.         System.out.println(num2);  
  51.     }  
  52.   
  53.     /** 
  54.      * check 静态检查函数 
  55.      */  
  56.     public void checkArgTest() {  
  57.   
  58.         try {  
  59.             String str1 = "sss";  
  60.             String str2 = null;  
  61.   
  62.             // 检查参数  
  63.             checkArgument(!"".equals(str1), "str is empty");  
  64.   
  65.             // 用来检查对象是否null。  
  66.             checkNotNull(str2, "str is null");  
  67.   
  68.             // 用来检查对象的某些状态。  
  69.             checkState(!"".equals(str1));  
  70.   
  71.             // 检查指针是否越界  
  72.             // checkElementIndex(int index, int size)  
  73.   
  74.             // 检查[start, end]表示的位置范围对某个列表、字符串或数组是否有效*  
  75.             // checkPositionIndexes(int start, int end, int size)  
  76.         } catch (Exception e) {  
  77.             e.printStackTrace();  
  78.         }  
  79.     }  
  80.   
  81.     /** 
  82.      * ComparisonChain 比较链 
  83.      */  
  84.     public int compareTo(A a1, A a2) {  
  85.         return ComparisonChain.start()  
  86.                 .compare(a1.getGender(), a2.getGender())  
  87.                 .compare(a1.getName(), a2.getName())  
  88.                 .result();  
  89.     }  
  90.   
  91.     /** 
  92.      * Ordering 排序器 
  93.      */  
  94.     public void orderTest(List<A> aList) {  
  95.   
  96.         // 多重排序组合,从后往前;按照age倒序  
  97.         Ordering<A> ordering = Ordering.natural().nullsFirst().onResultOf(new Function<A, Integer>() {  
  98.             public Integer apply(A a) {  
  99.                 return a.getAge();  
  100.             }  
  101.         });  
  102.   
  103.         // 字符串长度排序:倒序  
  104.         Ordering<String> byLengthOrdering = new Ordering<String>() {  
  105.             public int compare(String left, String right) {  
  106.                 return Ints.compare(left.length(), right.length());  
  107.             }  
  108.         };  
  109.   
  110.         // 字符串长度排序-->取名字排序  
  111.         Ordering<A> byLengthOrdering2 = new Ordering<A>() {  
  112.             public int compare(A left, A right) {  
  113.                 return Ints.compare(left.getName().length(), right.getName().length());  
  114.             }  
  115.         };  
  116.   
  117.         // 获取排序结果  
  118.         List<A> result = byLengthOrdering2.greatestOf(aList.iterator(), aList.size());  
  119.   
  120.         // 获取排序后的前2个结果  
  121.         List<A> result2 = ordering.greatestOf(aList.iterator(), 2);  
  122.   
  123.         // 返回排序结果最小的那个(按名字)  
  124.         A aa = byLengthOrdering2.min(aList.iterator());  
  125.   
  126.         // 判断是否准确排序  
  127.         // boolean is = ordering.isOrdered((Iterable<A>) aList.iterator());  
  128.     }  
  129.   
  130.     /** 
  131.      * ImmutableList:不可变集合 
  132.      */  
  133.     public void immutableCollectionTest() {  
  134.         List<String> temp = new ArrayList<>();  
  135.         temp.add("m");  
  136.         temp.add("n");  
  137.   
  138.         // 获取不可变集合,下面三种效果相似  
  139.         List<String> list = ImmutableList.<String>builder().addAll(temp).build();  
  140.         List<String> list2 = ImmutableList.copyOf(temp);  
  141.         List<String> list3 = ImmutableList.of("a""b");  
  142.   
  143.         // 若在执行下面操作不允许  
  144.         // list3.add("c");  
  145.     }  
  146.   
  147.     /** 
  148.      * 新型集合扩展 
  149.      */  
  150.     public void collectionTest() {  
  151.         // 1. Multiset:可以添加相同元素,提供count计数方案  
  152.         Multiset<String> mutiSet = HashMultiset.create();  
  153.         mutiSet.add("swx");  
  154.         mutiSet.add("swx1");  
  155.         mutiSet.add("swx2");  
  156.         mutiSet.add("swx1");  
  157.         mutiSet.add("swx3"5);  
  158.         mutiSet.setCount("swx4"5);  
  159.   
  160.         // count(T):计数  
  161.         int count = mutiSet.count("swx5");  
  162.   
  163.         // elementSet():返回不重复的元素  
  164.         Set<String> set = mutiSet.elementSet();  
  165.   
  166.   
  167.         // 2.Multimap:一key对多value  
  168.         Multimap<String, String> multiMap = HashMultimap.create();  
  169.         multiMap.put("key1""key1");  
  170.         multiMap.put("key1""key11");  
  171.         multiMap.put("key1""key111");  
  172.         multiMap.put("key2""key2");  
  173.   
  174.         // asMap():返回Map<K,Collection<V>>形式的视图  
  175.         Map<String, Collection<String>> mmap = multiMap.asMap();  
  176.   
  177.         // keySet():返回不同的key  
  178.         Set<String> keySet = multiMap.keySet();  
  179.   
  180.         // keys():用Multiset表示Multimap中的所有键,每个键重复出现的次数等于它映射的值的个数  
  181.         Multiset<String> keyMutiliSet = multiMap.keys();  
  182.   
  183.         // values():用一个”扁平”的Collection<V>包含Multimap中的所有值  
  184.         Collection<String> values = multiMap.values();  
  185.   
  186.         // 移除操作  
  187.         multiMap.remove("key1""key1");  
  188.         multiMap.removeAll("key1");  
  189.   
  190.   
  191.         // 3.BiMap双向map  
  192.         HashBiMap<Integer, String> isMap = HashBiMap.create();  
  193.         isMap.put(1"str1");  
  194.         isMap.put(2"str2");  
  195.   
  196.         // inverse():倒转key:value  
  197.         BiMap<String, Integer> newMap = isMap.inverse();  
  198.   
  199.     }  
  200.   
  201.     /** 
  202.      * Lists、Maps等集合工具 
  203.      */  
  204.     public void newCollectionUtilTest() {  
  205.         // 初始化一个集合  
  206.         List<String> list = Lists.newArrayList();  
  207.         Map<String, String> map = Maps.newHashMap();  
  208.         Set<String> set = Sets.newHashSet();  
  209.         list = Lists.newArrayList("1""2""3");  
  210.   
  211.         // 将list按指定大小分隔  
  212.         List<List<String>> newLists = Lists.partition(list, 1);  
  213.         // 翻转list元素  
  214.         list = Lists.reverse(list);  
  215.   
  216.         // 对不可变集合进行反转  
  217.         list = ImmutableList.of("4""5""6");  
  218.         ImmutableList t = ImmutableList.copyOf(list);  
  219.         ImmutableList<String> iList = t.reverse();  
  220.   
  221.         List<A> aList = initData();  
  222.   
  223.         // 函数式编程  
  224.         // 提取所有对象主键  
  225.         Set<Integer> itemIdSet = FluentIterable.from(aList).transform(new Function<A, Integer>() {  
  226.             @Override  
  227.             public Integer apply(A a) {  
  228.                 return a.getAge();  
  229.             }  
  230.         }).toSet();  
  231.   
  232.         // 将集合按照主键映射成map,场景:主键唯一  
  233.         Map<String, A> aMap = Maps.uniqueIndex(aList, new Function<A, String>() {  
  234.             @Nullable  
  235.             @Override  
  236.             public String apply(A a) {  
  237.                 return a.getName();  
  238.             }  
  239.         });  
  240.   
  241.         // 将集合按照主键映射成map,场景:主键不唯一  
  242.         // Multimaps.index(Iterable, Function);  
  243.   
  244.         // 比较两个Map  
  245.         MapDifference diff = Maps.difference(new HashMap(), new HashMap());  
  246.         diff.entriesInCommon();// 两个Map中都有的映射项,包括匹配的键与值  
  247.         diff.entriesDiffering();// 键相同但是值不同值映射项。返回的Map的值类型  
  248.         diff.entriesOnlyOnLeft();// 键只存在于左边Map的映射项  
  249.         diff.entriesOnlyOnRight();// 键只存在于右边Map的映射项  
  250.   
  251.         // 返回两个multiSet的交集  
  252.         Multiset multiSet = Multisets.intersection(HashMultiset.create(), HashMultiset.create());  
  253.   
  254.         // map反转操作  
  255.         ArrayListMultimap<String, Integer> multimap = ArrayListMultimap.create();  
  256.         multimap.putAll("b", Ints.asList(246));  
  257.         multimap.putAll("a", Ints.asList(421));  
  258.         multimap.putAll("c", Ints.asList(253));  
  259.         TreeMultimap<Integer, String> inverse = Multimaps.invertFrom(multimap, TreeMultimap.<Integer, String>create());  
  260.         //1 => {"a"},2 => {"a", "b", "c"} ,3 => {"c"},4 => {"a", "b"},5 => {"c"}, 6 => {"b"}  
  261.   
  262.         // forMap(Map):Map包装成SetMultimap  
  263.         Map<String, Integer> map2 = ImmutableMap.of("a"1"b"1"c"2);  
  264.         SetMultimap<String, String> multimap2 = Multimaps.forMap(map);  
  265.         // multimap:["a" => {1}, "b" => {1}, "c" => {2}]  
  266.         Multimap<Integer, String> inverse2 = Multimaps.invertFrom(multimap, HashMultimap.<Integer, String>create());  
  267.         // inverse:[1 => {"a","b"}, 2 => {"c"}]  
  268.   
  269.         // 自定义Multimap的方法允许你指定Multimap中的特定实现  
  270. //        ListMultimap<String, Integer> myMultimap = Multimaps.newListMultimap(  
  271. //                Maps.<String, Collection>newTreeMap(),  
  272. //                new Supplier<LinkedList>() {  
  273. //                    public LinkedList get() {  
  274. //                        return Lists.newLinkedList();  
  275. //                    }  
  276. //                });  
  277.   
  278.     }  
  279.   
  280.     /** 
  281.      * Forwarding装饰着,加强默认的get、add等行为 
  282.      */  
  283.     class AddLoggingList<E> extends ForwardingList<E> {  
  284.         final List<E> delegate; // backing list  
  285.         AddLoggingList(List<E> delegate) {  
  286.             this.delegate = delegate;  
  287.         }  
  288.   
  289.         @Override  
  290.         protected List<E> delegate() {  
  291.             return delegate;  
  292.         }  
  293.   
  294.         @Override  
  295.         public void add(int index, E elem) {  
  296.             System.out.println("add a elem at index");  
  297.             super.add(index, elem);  
  298.         }  
  299.         @Override  
  300.         public boolean add(E elem) {  
  301.             System.out.println("add a elem");  
  302.             return standardAdd(elem); // 用add(int, E)实现  
  303.         }  
  304.         @Override  
  305.         public boolean addAll(Collection<? extends E> c) {  
  306.             System.out.println("add all elem");  
  307.             return standardAddAll(c); // 用add实现  
  308.         }  
  309.     }  
  310.   
  311.     /** 
  312.      * Forwarding装饰者,加强默认的get、add等行为测试 
  313.      */  
  314.     public void forwardingTest(){  
  315.         List<String> list = new ArrayList<>();  
  316.         AddLoggingList<String> listWrap = new AddLoggingList(list);  
  317.         listWrap.add("1");  
  318.         System.out.println(list.size());  
  319.     }  
  320.   
  321.     /** 
  322.      * PeekingIterator装饰者,事先窥视[peek()]到下一次调用next()返回的元素。 
  323.      * 复制一个List,并去除连续的重复元素。 
  324.      */  
  325.     public void peekingIteratorTest(){  
  326.         List<String> source = new ArrayList<>();  
  327.         List<String> result = Lists.newArrayList();  
  328.         PeekingIterator<String> iter = Iterators.peekingIterator(source.iterator());  
  329.         while (iter.hasNext()) {  
  330.             String current = iter.next();  
  331.             while (iter.hasNext() && iter.peek().equals(current)) {  
  332.                 //跳过重复的元素  
  333.                 iter.next();  
  334.             }  
  335.             result.add(current);  
  336.         }  
  337.     }  
  338.   
  339.     public static void main(String args[]) {  
  340.         GuavaTest t = new GuavaTest();  
  341.         t.forwardingTest();  
  342.     }  
  343.   
  344.     public List<A> initData() {  
  345.         A a1 = new A();  
  346.         a1.setAge(22);  
  347.         a1.setGender("sex");  
  348.         a1.setName("swx1");  
  349.   
  350.         A a2 = new A();  
  351.         a2.setAge(20);  
  352.         a2.setGender("sex");  
  353.         a2.setName("swx123");  
  354.   
  355.         A a3 = new A();  
  356.         a3.setAge(25);  
  357.         a3.setGender("sex");  
  358.         a3.setName("swx32");  
  359.   
  360.         List<A> list = new ArrayList<>();  
  361.         list.add(a1);  
  362.         list.add(a2);  
  363.         list.add(a3);  
  364.   
  365.         return list;  
  366.     }  
  367.   
  368.     class A {  
  369.         @Nullable  
  370.         private int age;  
  371.         private String name;  
  372.         private String gender;  
  373.   
  374.         public int getAge() {  
  375.             return age;  
  376.         }  
  377.   
  378.         public void setAge(int age) {  
  379.             this.age = age;  
  380.         }  
  381.   
  382.         public String getName() {  
  383.             return name;  
  384.         }  
  385.   
  386.         public void setName(String name) {  
  387.             this.name = name;  
  388.         }  
  389.   
  390.         public String getGender() {  
  391.             return gender;  
  392.         }  
  393.   
  394.         public void setGender(String gender) {  
  395.             this.gender = gender;  
  396.         }  
  397.     }  
  398. }  
[java]  view plain  copy
  1. /** 
  2.      * LoadingCache:缓存的使用 
  3.      * ExecutionException是一个包装异常 
  4.      */  
  5.     public void loadCacheTest() throws ExecutionException {  
  6.         final Map<Integer, String> map = ImmutableMap.of(1"v1"2"v2"3"v3"4"v4"5"v5");  
  7.         LoadingCache<Integer, String> cache = CacheBuilder.newBuilder()  
  8.                 .maximumSize(1000)   // 缓存大小  
  9.                 .expireAfterAccess(1000, TimeUnit.MINUTES)  // 缓存项在给定时间内没有被读/写访问,则回收。  
  10.                 .expireAfterWrite(100000, TimeUnit.MINUTES)  // 缓存项在给定时间内没有被读,则回收。  
  11.                 .removalListener(new RemovalListener<Integer, String>() { // 自定义移除监听器  
  12.                     public void onRemoval(RemovalNotification<Integer, String> removal) {  
  13.                         System.out.println("remove...");  
  14.                         System.out.println(removal.getValue());  
  15.                     }  
  16.                 })  
  17.                 .recordStats()// 开启统计功能  
  18.                 .build(new CacheLoader<Integer, String>() {   // 自定义加载器,若缓存中没有匹配到则从原数据集中加载,同时进缓存  
  19.                     public String load(Integer key) throws Exception {  
  20.                         System.out.println("load...");  
  21.                         return map.get(key);  
  22.                     }  
  23.                 });  
  24.   
  25.   
  26.   
  27.   
  28.         String v5 = cache.get(3);// 获取缓存数据,没有就会加载  
  29.         String v55 = cache.getIfPresent(5);// 获取缓存数据,没有不会加载  
  30.         Map amap = cache.asMap(); //包含当前所有加载到缓存的项,不包含没有加载的  
  31.   
  32.   
  33.         CacheStats status = cache.stats(); // 开启统计功能后获取统计信息  
  34.         double count =  status.hitRate();// 命中率  
  35.         double time = status.averageLoadPenalty(); // 加载新值平均时间  
  36.   
  37.   
  38.         cache.invalidate(2);// 单个移除  
  39.         cache.invalidateAll(ImmutableList.of(1,2,3));  // 批量移除  
  40.         cache.invalidateAll();  // 清空缓存  
  41.   
  42.   
  43.     }  
[java]  view plain  copy
  1. import com.google.common.eventbus.AsyncEventBus;  
  2. import com.google.common.eventbus.EventBus;  
  3. import com.google.common.eventbus.Subscribe;  
  4.   
  5. import java.util.concurrent.Executors;  
  6.   
  7. /** 
  8.  * 事件总线 
  9.  * Created by shiwenxue on 16/7/17. 
  10.  */  
  11. public class GuavaTest {  
  12.   
  13.     private static EventBus eventBus = null;  
  14.   
  15.     public GuavaTest(){  
  16.         // 初始化事件总线,同步事件总线  
  17.         eventBus = new EventBus();  
  18.         // 异步事件总线  
  19.         eventBus = new AsyncEventBus(Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()));  
  20.         // 注册事件监听器到事件总线  
  21.         eventBus.register(new MyEventBus());  
  22.     }  
  23.   
  24.     /** 
  25.      * 监听器 
  26.      * 一个监听器可以监听很多事件对象 
  27.      * 比如这个监听器就会监听3个事件对象 
  28.      * */  
  29.     class MyEventBus {  
  30.         @Subscribe  
  31.         public void myEventHandle1(MyEvent1 event1) {  
  32.             try {  
  33.                 Thread.sleep(1000);  
  34.             } catch (InterruptedException e) {  
  35.             }  
  36.             System.out.println("this is event1");  
  37.         }  
  38.   
  39.         @Subscribe  
  40.         public void myEventHandle2(MyEvent2 event2) {  
  41.             System.out.println("this is event2");  
  42.         }  
  43.   
  44.         @Subscribe  
  45.         public void myEventHandle3(MyEvent3 event3) {  
  46.             System.out.println("this is event3");  
  47.         }  
  48.     }  
  49.   
  50.   
  51.     /** 
  52.      * 事件1 
  53.      * */  
  54.     static class MyEvent1 {  
  55.   
  56.     }  
  57.   
  58.     /** 
  59.      * 事件2 
  60.      * */  
  61.     static class MyEvent2 {  
  62.   
  63.     }  
  64.   
  65.     /** 
  66.      * 事件3 
  67.      * */  
  68.     static class MyEvent3 {  
  69.   
  70.     }  
  71.   
  72.     public static void  main(String args[]){  
  73.         GuavaTest t = new GuavaTest();  
  74.         // 分发事件  
  75.         eventBus.post(new MyEvent1());  
  76.         eventBus.post(new MyEvent2());  
  77.         System.out.println(1);  
  78.     }  
  79. }  
[java]  view plain  copy
  1. package cn.gov.zcy.admin;  
  2.   
  3.   
  4. import com.google.common.base.Function;  
  5. import com.google.common.collect.Lists;  
  6. import com.google.common.util.concurrent.*;  
  7.   
  8. import javax.annotation.Nullable;  
  9. import java.util.List;  
  10. import java.util.concurrent.Executors;  
  11.   
  12. /** 
  13.  * ListenableFuture 并发编程测试 
  14.  * Created by shiwenxue on 16/7/22. 
  15.  */  
  16. public class ListenableFutureTest {  
  17.   
  18.   
  19.     //    private static ExecutorService executorService = Executors.newFixedThreadPool(2);  
  20.     private static ListeningExecutorService service = null;  
  21.   
  22.     static {  
  23.         service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(4));  
  24.     }  
  25.   
  26.     /** 
  27.      * 监听一个任务 
  28.      * 任务执行回调,可以根据任务成功与失败分别进行执行回调 
  29.      */  
  30.     public void listenOneFuture(final ListenableFuture future) {  
  31.         Futures.addCallback(future, new FutureCallback() {  
  32.             @Override  
  33.             public void onSuccess(@Nullable Object result) {  
  34.                 try {  
  35.                     System.out.println("task success finish");  
  36.                 } catch (Exception e) {  
  37.                     e.printStackTrace();  
  38.                 }  
  39.             }  
  40.   
  41.             @Override  
  42.             public void onFailure(Throwable t) {  
  43.                 System.out.println("task failed finish");  
  44.             }  
  45.         });  
  46.     }  
  47.   
  48.     /** 
  49.      * 监听多个任务 
  50.      */  
  51.     public void listenFutures(Iterable futures) throws Exception {  
  52.   
  53.         // Futures.allAsList(Iterable<ListenableFuture<V>>) 返回所有的ListenableFuture,失败用null代替  
  54.         ListenableFuture allQueries = Futures.allAsList(futures);  
  55.   
  56.         // Futures.successfulAsList(Iterable<ListenableFuture<V>>)  返回所有成功的ListenableFuture,有一个失败将会进入失败  
  57.         ListenableFuture successfulQueries = Futures.successfulAsList(futures);  
  58.   
  59.         // 监听任务执行情况  
  60.         Futures.addCallback(successfulQueries, new FutureCallback<Object>() {  
  61.             @Override  
  62.             public void onSuccess(Object arg0) {  
  63.                 System.out.println(arg0);  
  64.                 System.out.println("tasks success finish");  
  65.             }  
  66.   
  67.             @Override  
  68.             public void onFailure(Throwable arg0) {  
  69.                 System.out.println(arg0);  
  70.             }  
  71.         });  
  72.   
  73.         // Futures.transform(ListenableFuture<A>, AsyncFunction<A, B>, Executor)* :返回一个新的ListenableFuture,对于ListenableFuture的返回值进行转换。  
  74.         final ListenableFuture transform = Futures.transform(allQueries, new Function<List<Integer>, ListenableFuture<String>>() {  
  75.   
  76.             @Nullable  
  77.             @Override  
  78.             public ListenableFuture<String> apply(@Nullable List<Integer> results) {  
  79.                 System.out.println(String.format("success future:%d", results.size()));  
  80.                 // immediateFuture: 立即返回一个待返回值的ListenableFuture。  
  81.                 return Futures.immediateFuture(String.format("success future:%d", results.size()));  
  82.             }  
  83.         });  
  84.   
  85.   
  86.         System.out.println(transform.get());  
  87.   
  88.   
  89.     }  
  90.   
  91.   
  92.     public static void main(String[] args) throws Exception {  
  93.         ListenableFutureTest t = new ListenableFutureTest();  
  94.         MyTask task1 = new MyTask();  
  95.         MyTask task2 = new MyTask();  
  96.         MyTask task3 = new MyTask();  
  97.   
  98.         // 获取ListenableFuture  
  99.         final ListenableFuture future1 = service.submit(task1);  
  100.         final ListenableFuture future2 = service.submit(task2);  
  101.         final ListenableFuture future3 = service.submit(task3);  
  102.   
  103.         Iterable futures = Lists.newArrayList(future1, future1, future2);  
  104.   
  105.         // 对一个任务进行监听  
  106.         t.listenOneFuture(future1);  
  107.         // 对多个任务同时监听  
  108.         t.listenFutures(futures);  
  109.   
  110.         // ListenableFuture 中的基础方法是addListener(Runnable, Executor), 该方法会在多线程运算完的时候,指定的Runnable参数传入的对象会被指定的Executor执行。  
  111.         future1.addListener(new Runnable() {  
  112.             @Override  
  113.             public void run() {  
  114.                 System.out.println("listener task has finished");  
  115.             }  
  116.         }, Executors.newFixedThreadPool(2));  
  117.   
  118.         System.out.println("main function has finished");  
  119.   
  120.     }  
  121.   
  122.     // 自定义任务执行  
  123.     static class MyTask implements Runnable {  
  124.   
  125.         @Override  
  126.         public void run() {  
  127.             try {  
  128.                 System.out.println("task is running");  
  129.                 Thread.sleep(5000);  
  130.             } catch (InterruptedException e) {  
  131.                 e.printStackTrace();  
  132.             }  
  133.         }  
  134.     }  
  135.   
  136.     // 自定义回调实现  
  137.     static class MyCallbackImpl implements FutureCallback {  
  138.   
  139.         @Override  
  140.         public void onSuccess(@Nullable Object result) {  
  141.             System.out.println(result);  
  142.         }  
  143.   
  144.         @Override  
  145.         public void onFailure(Throwable t) {  
  146.             throw new RuntimeException(t.getMessage());  
  147.         }  
  148.     }  
  149.   
  150.   
  151. }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值