public static void main(String[] args) { main3(args); }
//(不阻塞主线程) public static void main1(String[] args) { CompletableFuture<Object> anyFuture = CompletableFuture .anyOf(Stream.of(1, 2, 3, 4, 5, 6, 7).map(integer -> CompletableFuture.supplyAsync(getStringSupplier(integer))).toArray(CompletableFuture[]::new)); System.out.println("结果---" + anyFuture.join()); System.out.println("主线程结束..."); try { Thread.sleep(100000); } catch (InterruptedException e) { e.printStackTrace(); } }
//(阻塞主线程) public static void main2(String[] args) { Optional<String> any = Stream.of(1, 2, 3, 4, 5, 6, 7).parallel().map(integer -> getStringSupplier(integer).get()).findAny(); System.out.println("结果---" + any.orElse("xxx")); System.out.println("主线程结束..."); try { Thread.sleep(100000); } catch (InterruptedException e) { e.printStackTrace(); } }
//(不阻塞主线程) public static void main3(String[] args) { List<CompletableFuture<String>> collect = Stream.of(1, 2, 3, 4, 5, 6, 7).map(integer -> CompletableFuture.supplyAsync(getStringSupplier(integer))) .collect(Collectors.toList()); Optional<String> any = collect.stream().map(CompletableFuture::join).filter(s -> s.contains("3..")).findAny(); System.out.println("结果---" + any.orElse("xxx")); System.out.println("主线程结束..."); try { Thread.sleep(100000); } catch (InterruptedException e) { e.printStackTrace(); } } private static Supplier<String> getStringSupplier(Integer integer) { return () -> { long millis = ThreadLocalRandom.current().nextLong(3000, 9000); try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } String s = integer + "..耗时(ms):" + millis; System.out.println(s); return s; }; }
main1的执行结果:(不阻塞主线程)
5..耗时(ms):3147 结果---5..耗时(ms):3147 主线程结束... 3..耗时(ms):3749 4..耗时(ms):4551 6..耗时(ms):5653 7..耗时(ms):7132 1..耗时(ms):7875 2..耗时(ms):8271
main2的执行结果:(阻塞主线程)
2..耗时(ms):3713 5..耗时(ms):4389 6..耗时(ms):4578 1..耗时(ms):4722 4..耗时(ms):5126 7..耗时(ms):5491 3..耗时(ms):5730 结果---2..耗时(ms):3713 主线程结束...
main3的执行结果(不阻塞主线程)
3..耗时(ms):3238 1..耗时(ms):3905 2..耗时(ms):4067 结果---3..耗时(ms):3238 主线程结束... 6..耗时(ms):5748 7..耗时(ms):6344 4..耗时(ms):7122 5..耗时(ms):7846
总结:Stream的parallel并行流在调用findAny的时候,仍然要等待所有执行结果结束后才会获取结果,获取结果前会阻塞主线程,这点在性能优化上应该引起关注。 其中main1和mian3都是不阻塞主线程,CompletableFuture.anyOf不支持筛选结果,通过CompletableFuture和Stream配合可以findAny高性能获取任意结果。
标签:Stream,..,主线,findAny,耗时,CompletableFuture,ms,integer From: https://www.cnblogs.com/wulm/p/16899038.html