java8 supplyasync_【新特性】java8新特性

本文深入介绍了Java8的新特性,重点讲解了如何使用CompletableFuture进行异步编程,包括supplyAsync、runAsync、allOf等方法的使用,以及结果变换、异常处理和流式编程等高级特性。示例代码展示了如何结合thenApply、thenAccept、thenCombine等方法实现复杂的异步操作,并给出了异常补偿和Stream API的应用实例。
摘要由CSDN通过智能技术生成

java8新特性

异步编程

CompletableFuture 实现异步编程

supplyAsync 有返回值

CompletableFuture f1 = CompletableFuture.supplyAsync(() -> "hello");

runAsync参数是Runable没有返回值

CompletableFuture runAsync = CompletableFuture.runAsync(() -> System.out.println("123"));

runAsync.get();

allof在f1和f2两个任务执行完成前一直阻塞,一般用于多个线程执行后获取执行结果

CompletableFuture f3 = CompletableFuture.supplyAsync(() -> "hello");

CompletableFuture f4 = CompletableFuture.supplyAsync(() -> "world");

CompletableFuture f5 = CompletableFuture.supplyAsync(() -> {

try {

TimeUnit.SECONDS.sleep(10);

} catch (InterruptedException e) {

e.printStackTrace();

}

return "!";

});

// 使用allOf方法

CompletableFuture.allOf(f3, f4, f5).join();

变换结果

​这些api用于上一个阶段的计算结果,然后对结果进行操作返回操作后的结果

thenApplyAsync 异步执行

thenApply 同步执行

//计算结果 helloworld

String s2 = CompletableFuture.supplyAsync(() -> "hello").thenApplyAsync(v -> v + "world").join();

消费结果

thenAccept 同步消费结果没有返回值

thenAcceptAsync 异步消费结果没有返回值

//打印出helloWord

CompletableFuture.supplyAsync(()->"hello").thenAcceptAsync(v-> System.out.println(v+"hello"));

结果转化

​thenCombine 获取多个结果转化

​thenCombineAsync

​thenAcceptBoth 当两个CompletionStage都执行完成后,把结果一块交给thenAcceptBoth来进行消耗

//结果:endStr = helloworld!!!

final String endStr = CompletableFuture.supplyAsync(() -> "hello")

.thenCombine(CompletableFuture.supplyAsync(() -> "world"), (str1, str2) -> str1 + str2)

.thenCombineAsync(CompletableFuture.supplyAsync(() -> "!!!"), (str3, str4) -> str3 + str4).join();

System.out.println("endStr = " + endStr);

谁执行快用谁

applyToEither

private static void applyToEither() throws Exception {

CompletableFuture f1 = CompletableFuture.supplyAsync(new Supplier() {

@Override

public Integer get() {

int t = new Random().nextInt(3);

try {

TimeUnit.SECONDS.sleep(t);

} catch (InterruptedException e) {

e.printStackTrace();

}

System.out.println("f1="+t);

return t;

}

});

CompletableFuture f2 = CompletableFuture.supplyAsync(new Supplier() {

@Override

public Integer get() {

int t = new Random().nextInt(3);

try {

TimeUnit.SECONDS.sleep(t);

} catch (InterruptedException e) {

e.printStackTrace();

}

System.out.println("f2="+t);

return t;

}

});

CompletableFuture result = f1.applyToEither(f2, new Function() {

@Override

public Integer apply(Integer t) {

System.out.println(t);

return t * 2;

}

});

System.out.println(result.get());

}

异常补偿

exceptionally 捕捉异常,相当于try-catch

Object errStr = CompletableFuture.supplyAsync(() -> {

throw new RuntimeException("error1");

}).thenApplyAsync((s) -> {

throw new RuntimeException("error2");

}).exceptionally((e) -> {

return e.getMessage();

}).join();

StreamApi中集合类的流式编程

filter过滤

strings.stream().filter(s -> !s.isEmpty()).forEach(System.out::println);

map 计算

strings.stream().map(s -> s+"1").forEach(System.out::println);

flateMap 将数组扁平化操作

String[] a = {"h","e","e","l","o"};

String[] b = {"w","o","r","l","d"};

final List strings = Arrays.asList(a, b);

System.out.println("strings before = " + strings);

List collect = strings.stream().flatMap(Arrays::stream).collect(Collectors.toList());

System.out.println("collect after = " + collect);

执行结果:

strings before = [[Ljava.lang.String;@4dc63996, [Ljava.lang.String;@d716361]

collect after = [h, e, e, l, o, w, o, r, l, d]

将内层数组全部抽离出来,将集合扁平化

sorted 排序

strings.stream().sorted((String o1, String o2) -> {

if (Integer.valueOf(o1) < Integer.valueOf(o2))

{

return 1;

}else {

return -1;

}

}).forEach(System.out::println);

distinct 消除重复

strings.stream().distinct().forEach(System.out::println);

最终操作

forEach 迭代每一个元素

strings.stream().map(s -> s+"1").forEach(System.out::println);

count 统计元素的个数

Integer[] strs = {1, 2, 3, 4};

List strings = Arrays.asList(strs);

final long count = strings.stream().count();

System.out.println("count = " + count); //结果 4

collect 汇总一个结果

Integer[] strs = {1, 2, 3,3, 4};

List strings = Arrays.asList(strs);

//去冲后的结果转为list

strings = strings.stream().distinct().collect(Collectors.toList());

System.out.println(strings.toString());

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值