java多线程执行有返回值的任务示例
public static void main(String[] args) throws Exception {
long startTime = System.currentTimeMillis();
//ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
Map<String, String> map = new HashMap<>();
ExecutorService executorService = Executors.newFixedThreadPool(10);
//final BlockingQueue<Future<String>> queue = new LinkedBlockingDeque<>(10);
//实例化CompletionService
//final CompletionService<String> completionService = new ExecutorCompletionService<>(executorService, queue);
//for (int i = 0; i < 10; i++) {
// int finalI = i;
// executorService.submit(new Callable<String>() {
// public String call() {
// return getResult(finalI);
// }
// });
//}
//
//// 输出结果
//for (int i = 0; i < 10; i++) {
// // 获取包含返回结果的future对象
// // (若整个阻塞队列中还没有一条线程返回结果,那么调用take将会被阻塞,
// // 当然你可以调用poll,不会被阻塞,若没有结果会返回null,poll和take返回正确的结果后会将该结果从队列中删除)
// Future<String> future = completionService.take();
// // 从future中取出执行结果,这里存储的future已经拥有执行结果,get不会被阻塞
// String result = future.get();
// System.out.println(result);
//}
//executorService.shutdown();
//for (int i = 0; i < 10; i++) {
// int finalI = i;
// executorService.submit(() -> {
// String result = getResult(finalI);
// map.put(String.valueOf(finalI), result);
// });
//}
//
//executorService.shutdown();
//while (!executorService.isTerminated()){
// Thread.sleep(1000);
// System.out.println("还没停止。。。");
//}
//System.out.println("全部执行完毕");
List<CompletableFuture<Void>> futures = new ArrayList<>();
for (int i = 0; i < 10; i++) {
int finalI = i;
CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
String result = getResult(finalI);
map.put(String.valueOf(finalI), result);
}, executorService);
futures.add(completableFuture);
}
CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])).join();
executorService.shutdown();
//for (int i = 0; i < 10; i++) {
// String result = getResult(i);
// map.put(String.valueOf(i), result);
//}
System.out.println("大小:" + map.size());
//System.out.println(map);
long endTime = System.currentTimeMillis();
System.out.println("耗时:" + (endTime - startTime));
}
public static String getResult(int i) {
try {
Thread.sleep(new Random().nextInt(500));
System.out.println(i);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
String result = "当前值:" + i;
return result;
}
参考:http://www.bryh.cn/a/388436.html、https://blog.csdn.net/hkk666123/article/details/131946695
欢迎一起来学习和指导,谢谢关注!
本文来自博客园,作者:xiexie0812,转载请注明原文链接:https://www.cnblogs.com/mask-xiexie/p/17897346.html