概述
import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.*; /** * Created by wk on 18/5/14/16:48. */ public class ConcurrentTest { public static void main(String args[]) { System.out.println("hello word."); final int size = 10; CountDownLatch countlatch=new CountDownLatch(size); Map<String, Long> concurrentHashMap = new ConcurrentHashMap<>(); List<Future<Long>> list = new ArrayList<>(); ExecutorService executorService = Executors.newCachedThreadPool(); for (int i = 0; i<size; i++) { Future<Long> ret = executorService.submit(new Task(countlatch, concurrentHashMap)); //Future.get Waits if necessary for the computation to complete, and then // * retrieves its result. 故此处不应该使用这种方式, // 他是在这等了,正确的用法时,把这些都放入list,等到都ready了再去read // System.out.println( "future " + ret.get()); // 阻塞的 list.add(ret); } try { countlatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } for (int i=0; i<size; i++) { try { System.out.println("future get" + list.get(i).get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } int index = 0; for (Map.Entry<String, Long> entry: concurrentHashMap.entrySet() ) { System.out.println("index : " + index ++ + " entry key " + entry.getKey() + ", value " + entry.getValue()); } } } class Task implements Callable<Long> { CountDownLatch countDownLatch; Map<String,Long> rets; public Task(CountDownLatch countDownLatch, Map<String,Long> rets) { this.countDownLatch = countDownLatch; this.rets = rets; } @Override public Long call() { Long id = Thread.currentThread().getId(); System.out.println("thread id " + id); // 这样用其实不太标准,毕竟这个时候有可能已经 count down,但还没有返回 this.rets.put(id + "", id); this.countDownLatch.countDown(); return new Long(id); } }
最后
以上就是动人音响为你收集整理的java future CountDownLatch 的使用的全部内容,希望文章能够帮你解决java future CountDownLatch 的使用所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复