1. 程式人生 > >Java8新特性之CompletableFuture詳解

Java8新特性之CompletableFuture詳解

jdk1.8中加入了CompletableFuture類來輔助實現非同步程式設計。上一節中提到了執行緒池執行非同步方法返回Fufure例項,但是當執行多個非同步任務時,如何判斷這些任務都已執行完畢則沒有好的辦法,只能通過定時輪詢去判斷這些任務isDone(),並且也需要建立執行緒池來實現。而新的CompletableFufure類則對非同步程式設計提供了一些很不錯的方法。如下: 靜態方法: CompletableFuture.runAsync(Runnable r);執行無返回值得非同步介面,返回CompletableFufure物件,get()方法是阻塞的。 CompletableFufure.supplyAsync(Supplier s);執行非同步有返回值的方法, CompletableFufure.allof(CompletableFufure...c) 一組非同步方法都執行成功時返回CompletableFuture方法。
CompletableFufure.anyOf(CompletableFufure...c
)一組非同步方法,有一個執行成功時就返回。 例項方法: thenAccept(Consumer c)執行成功之後執行的方法 thenApply(Function f )執行成功之後執行有引數的方法 thenCompose(T t,Function f )執行成功後攜帶引數執行方法 thenCombine()與第二個非同步方法合併,都執行成功後執行其他 參考程式碼:
package com.example.thread;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class CompletableFutureTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
Long start = System.currentTimeMillis();
CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(2000
);
} catch (InterruptedException e) {
e.printStackTrace();
}
return new Random().nextInt(10);
});
CompletableFuture<Integer> completableFuture1 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 3;
});
CompletableFuture<Integer> completableFuture2 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 5;
});
System.out.println("start");
CompletableFuture anyOf = CompletableFuture.anyOf(completableFuture, completableFuture1, completableFuture2);
System.out.println(anyOf.get());
System.out.println("execute time:" + (System.currentTimeMillis() - start));
System.out.println(completableFuture.isDone());
System.out.println(completableFuture1.isDone());
System.out.println(completableFuture2.isDone());
CompletableFuture allOf = CompletableFuture.allOf(completableFuture, completableFuture1, completableFuture2);
CompletableFuture completableFuture3 = CompletableFuture.runAsync(new Runnable() {
@Override
public void run() {
System.out.println("runAsync");
}
});
System.out.println(allOf.get());
System.out.println("execute time:" + (System.currentTimeMillis() - start));
System.out.println(completableFuture.isDone());
System.out.println(completableFuture1.isDone());
System.out.println(completableFuture2.isDone());
//
Integer s = completableFuture2.thenCompose(resInt -> CompletableFuture.supplyAsync(() -> resInt + 123)).get();
Integer s2 = completableFuture1.thenCombine(completableFuture2, (int1, int2) -> int1 + int2).get();
System.out.println(s2);
System.out.println(s);
}
}