对计算速度进行选用
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class Test4 {
public static void main(String[] args) {
CompletableFuture<String> a = CompletableFuture.supplyAsync(() -> {
try { TimeUnit.SECONDS.sleep(4); } catch (InterruptedException e) {e.printStackTrace();}
return "a";
});
CompletableFuture<String> b = CompletableFuture.supplyAsync(() -> {
try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) {e.printStackTrace();}
return "b";
});
//谁快用谁
CompletableFuture<String> result = a.applyToEither(b, f -> {
return f;
});
System.out.println(result.join());
}
}
对计算结果进行合并
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class Test4 {
public static void main(String[] args) {
CompletableFuture<Integer> a = CompletableFuture.supplyAsync(() -> {
try { TimeUnit.SECONDS.sleep(4); } catch (InterruptedException e) {e.printStackTrace();}
return 10;
});
CompletableFuture<Integer> b = CompletableFuture.supplyAsync(() -> {
try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) {e.printStackTrace();}
return 20;
});
//等待俩者结果一起返回
CompletableFuture<Integer> result = a.thenCombine(b, (x,y) -> {
return x + y;
});
System.out.println(result.join());
}
}