Java8新特性:CompletableFuture 方法介绍

目录

1. runAsync 和 supplyAsync方法

2. whenComplete、whenCompleteAsync、exceptionally

3. thenApply 、 handle

thenApply

handle

4.thenAccept 、thenRun 方法 消费处理结果 

thenAccept

 thenRun

5. thenCombine 、 thenAcceptBoth 

thenCombine

thenAcceptBoth

 6.applyToEither 、 acceptEither

 applyToEither

 acceptEither

 7. runAfterEither 、 runAfterBoth 

runAfterEither

runAfterBoth

 8.complete

9.allOf 多实例同时返回 、anyOf 多实例一个执行完成返回

allOf

anyOf

 



1. runAsync 和 supplyAsync方法

  • runAsync方法不支持返回值。
  • supplyAsync可以支持返回值。

 

public static CompletableFuture<Void> runAsync(Runnable runnable)
public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)

 默认使用 ForkJoinPool.commonPool() 线程池执行,

runAsync使用(包含lambda调用方法)

	public static void runAsync() throws Exception {CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("执行完成");});future.get();}public static void runAsync2() throws Exception {CompletableFuture<Void> future = CompletableFuture.runAsync(new Runnable() {@Overridepublic void run() {try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("执行完成");}});future.get();}

supplyAsync使用

	public static void supplyAsync() throws Exception {         CompletableFuture<Long> future = CompletableFuture.supplyAsync(() -> {try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("执行完成");return System.currentTimeMillis();});long time = future.get();System.out.println("time = "+time);}public static void supplyAsync2() throws Exception {         CompletableFuture<Long> future = CompletableFuture.supplyAsync(new Supplier<Long>() {@Overridepublic Long get() {try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("执行完成");return System.currentTimeMillis();}});long time = future.get();System.out.println("time = "+time);}

 

 

2. whenComplete、whenCompleteAsync、exceptionally

计算完成后执行的回调方法

 

public CompletableFuture<T> whenComplete(BiConsumer<? super T,? super Throwable> action)
public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super Throwable> action)
public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super Throwable> action, Executor executor)
public CompletableFuture<T> exceptionally(Function<Throwable,? extends T> fn)

whenComplete 和 whenCompleteAsync 的区别:

whenComplete:是执行当前任务的线程执行继续执行 whenComplete 的任务。

whenCompleteAsync:是执行把 whenCompleteAsync 这个任务继续提交给线程池来进行执行。

exceptionally:异常处理方法

	public static void whenComplete() throws Exception {CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {}if(new Random().nextInt()%2>0) {int i = 1/0;}});future.whenComplete(new BiConsumer<Void, Throwable>() {@Overridepublic void accept(Void t, Throwable action) {System.out.println("执行完成!");}});future.exceptionally(new Function<Throwable, Void>() {@Overridepublic Void apply(Throwable t) {System.out.println("执行失败!"+t.getMessage());return null;}});future.get();}public static void whenComplete2() throws Exception {String string = CompletableFuture.supplyAsync(() -> {try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {}if(new Random().nextInt()%2>0) {int i = 1/0;}return "返回结果";}).whenComplete((value,throwable)->{if(throwable!=null) {System.out.println("异常:"+throwable);}else {System.out.println("value:"+value);}}).get();System.out.println("执行完:"+string);
//	    future.exceptionally(new Function<Throwable, Void>() {
//	        @Override
//	        public Void apply(Throwable t) {
//	            System.out.println("执行失败!"+t.getMessage());
//	            return null;
//	        }
//	    });}

 

3. thenApply 、 handle

thenApply

 

串行执行,第二次执行需要依赖第一次的执行结果

	private static void thenApply() throws Exception {CompletableFuture<Integer> future = CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic Integer get() {try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}if(new Random().nextInt()%2>0) {int i = 1/0;}return 10;}}).thenApply(new Function<Integer, Integer>() {@Overridepublic Integer apply(Integer value) {System.out.println("上一步结果:"+value);System.out.println("返回结果:"+20);return 20;}}).exceptionally(new Function<Throwable, Integer>() {@Overridepublic Integer apply(Throwable t) {System.out.println("异常返回:"+ t);return -1;}});long result = future.get();System.out.println("最终结果:"+result);}private static void thenApply2() throws Exception {Integer integer = CompletableFuture.supplyAsync(()->{try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {}if(new Random().nextInt()%2>0) {int i = 1/0;}return 10;}).thenApply((value)->{System.out.println("上一步结果:"+value);System.out.println("返回结果:"+20);return 20;}).exceptionally((throwable)->{System.out.println("异常返回:"+throwable);return -1;}).get();System.out.println("最终结果:"+integer);}

 

handle

handle 是执行任务完成时对结果的处理。

handle 方法和 thenApply 方法处理方式基本一样。不同的是 handle 是在任务完成后再执行,还可以处理异常的任务。thenApply 只可以执行正常的任务,任务出现异常则不执行 thenApply 方法。

 

public <U> CompletionStage<U> handle(BiFunction<? super T, Throwable, ? extends U> fn);
public <U> CompletionStage<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn);
public <U> CompletionStage<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn,Executor executor);
	public static void handle() throws Exception{CompletableFuture<Integer> future = CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic Integer get() {int i= 10/0;return new Random().nextInt(10);}}).handle(new BiFunction<Integer, Throwable, Integer>() {@Overridepublic Integer apply(Integer param, Throwable throwable) {int result = -1;if(throwable==null){result = param * 2;}else{System.out.println(throwable.getMessage());}return result;}});System.out.println(future.get());}public static void handle2() throws Exception{CompletableFuture<Integer> future = CompletableFuture.supplyAsync(()->{int i= 10/0;return new Random().nextInt(10);}).handle((value,throwable)->{int result = -1;if(throwable==null){result = value * 2;}else{System.out.println(throwable.getMessage());}return result;});System.out.println(future.get());}

4.thenAccept 、thenRun 方法 消费处理结果 

 

thenAccept

接收任务的处理结果,并消费处理,无返回结果。

 

public CompletionStage<Void> thenAccept(Consumer<? super T> action);
public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action);
public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action,Executor executor);

 

	public static void thenAccept() throws Exception{CompletableFuture<Void> future = CompletableFuture.supplyAsync(()->{return new Random().nextInt(10);}).thenAccept(integer -> {System.out.println(integer);});future.get();}public static void thenAccept2() throws Exception{CompletableFuture<Void> future = CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic Integer get() {return new Random().nextInt(10);}}).thenAccept(new Consumer<Integer>() {@Overridepublic void accept(Integer t) {System.out.println(t);}});future.get();}

 thenRun

该方法同 thenAccept 方法类似。不同的是上个任务处理完成后,并不会把计算的结果传给 thenRun 方法。只是处理完任务后,执行 thenAccept 的后续操作。

 

 

public CompletionStage<Void> thenRun(Runnable action);
public CompletionStage<Void> thenRunAsync(Runnable action);
public CompletionStage<Void> thenRunAsync(Runnable action,Executor executor);

 

	public static void thenRun() throws Exception{CompletableFuture<Void> future = CompletableFuture.supplyAsync(new Supplier<String>() {@Overridepublic String get() {return "第一步完成";}}).thenRun(new Runnable() {@Overridepublic void run() {System.out.println("执行完成");}});future.get();}public static void thenRun2() throws Exception{CompletableFuture<Void> future = CompletableFuture.supplyAsync(()->{return "第一步完成";}).thenRun(() -> {System.out.println("执行完成");});future.get();}

 

 

5. thenCombine 、 thenAcceptBoth 

合并两个任务执行结果,进行操作

thenCombine

 

thenCombine 会把 两个 CompletionStage 的任务都执行完成后,把两个任务的结果一块交给 thenCombine 来处理。

 

public <U,V> CompletionStage<V> thenCombine(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn);
public <U,V> CompletionStage<V> thenCombineAsync(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn);
public <U,V> CompletionStage<V> thenCombineAsync(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn,Executor executor);
	private static void thenCombine() throws Exception {CompletableFuture<String> future1 = CompletableFuture.supplyAsync(new Supplier<String>() {@Overridepublic String get() {try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}return "hello";}});CompletableFuture<String> future2 = CompletableFuture.supplyAsync(new Supplier<String>() {@Overridepublic String get() {return "world";}});CompletableFuture<String> result = future1.thenCombine(future2, new BiFunction<String, String, String>() {@Overridepublic String apply(String t, String u) {return t+" "+u;}});System.out.println(result.get());}private static void thenCombine2() throws Exception {CompletableFuture<String> future1 = CompletableFuture.supplyAsync(()->{try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {e.printStackTrace();}return "hello";});CompletableFuture<String> future2 = CompletableFuture.supplyAsync(()->{return "world";});CompletableFuture<String> result = future1.thenCombine(future2, (v1,v2)->{return v1+" "+v2;});System.out.println(result.get());}

 

thenAcceptBoth

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

与 thenCombine 区别在于,thenAcceptBoth无返回值

 

public <U> CompletionStage<Void> thenAcceptBoth(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action);
public <U> CompletionStage<Void> thenAcceptBothAsync(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action);
public <U> CompletionStage<Void> thenAcceptBothAsync(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action,     Executor executor);

 

	private static void thenAcceptBoth() throws Exception {CompletableFuture<String> future1 = CompletableFuture.supplyAsync(new Supplier<String>() {@Overridepublic String get() {try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}return "hello";}});CompletableFuture<String> future2 = CompletableFuture.supplyAsync(new Supplier<String>() {@Overridepublic String get() {return "world";}});future1.thenAcceptBoth(future2, new BiConsumer<String, String>() {@Overridepublic void accept(String t, String u) {System.out.println( t+" "+u);}});}private static void thenAcceptBoth2() throws Exception {CompletableFuture<String> future1 = CompletableFuture.supplyAsync(()->{try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}return "hello";});CompletableFuture<String> future2 = CompletableFuture.supplyAsync(()->{return "world";});future1.thenAcceptBoth(future2, (v1,v2)->{System.out.println( v1+" "+v2);});}

 6.applyToEither 、 acceptEither

两个CompletionStage,谁执行返回的结果快,就用那个CompletionStage的结果进行下一步的转化操作。

 applyToEither 有返回值,acceptEither 无返回值

 applyToEither

public <U> CompletionStage<U> applyToEither(CompletionStage<? extends T> other,Function<? super T, U> fn);
public <U> CompletionStage<U> applyToEitherAsync(CompletionStage<? extends T> other,Function<? super T, U> fn);
public <U> CompletionStage<U> applyToEitherAsync(CompletionStage<? extends T> other,Function<? super T, U> fn,Executor executor);
	private static void applyToEither() throws Exception {CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic 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<Integer> f2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic 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<Integer> result = f1.applyToEither(f2, new Function<Integer, Integer>() {@Overridepublic Integer apply(Integer t) {System.out.println(t);return t * 2;}});System.out.println("结果:"+result.get());}private static void applyToEither2() throws Exception {CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(()->{int t = new Random().nextInt(3);try {TimeUnit.SECONDS.sleep(t);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("f1="+t);return t;});CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(()->{int t = new Random().nextInt(3);try {TimeUnit.SECONDS.sleep(t);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("f2="+t);return t;});CompletableFuture<Integer> result = f1.applyToEither(f2, (value)->{System.out.println(value);return value * 2;});System.out.println("结果:"+result.get());}

 acceptEither

public CompletionStage<Void> acceptEither(CompletionStage<? extends T> other,Consumer<? super T> action);
public CompletionStage<Void> acceptEitherAsync(CompletionStage<? extends T> other,Consumer<? super T> action);
public CompletionStage<Void> acceptEitherAsync(CompletionStage<? extends T> other,Consumer<? super T> action,Executor executor);
	private static void acceptEither() throws Exception {CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic 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<Integer> f2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic 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<Void> acceptEither = f1.acceptEither(f2, new Consumer<Integer>() {@Overridepublic void accept(Integer t) {System.out.println("结果:"+t);}});}private static void acceptEither2() throws Exception {CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(()->{int t = new Random().nextInt(3);try {TimeUnit.SECONDS.sleep(t);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("f1="+t);return t;});CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(()->{int t = new Random().nextInt(3);try {TimeUnit.SECONDS.sleep(t);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("f2="+t);return t;});CompletableFuture<Void> acceptEither = f1.acceptEither(f2, (value)->{System.out.println("结果:"+value);});}

 7. runAfterEither 、 runAfterBoth 

runAfterEither

两个CompletionStage,任何一个完成了都会执行下一步的操作

 

public CompletionStage<Void> runAfterEither(CompletionStage<?> other,Runnable action);
public CompletionStage<Void> runAfterEitherAsync(CompletionStage<?> other,Runnable action);
public CompletionStage<Void> runAfterEitherAsync(CompletionStage<?> other,Runnable action,Executor executor);
	private static void runAfterEither() throws Exception {CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic 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<Integer> f2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic 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;}});f1.runAfterEither(f2, new Runnable() {@Overridepublic void run() {System.out.println("上面有一个已经完成了。");}}).get();}private static void runAfterEither1() throws Exception {CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(()->{int t = new Random().nextInt(3);try {TimeUnit.SECONDS.sleep(t);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("f1="+t);return t;});CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(()->{int t = new Random().nextInt(3);try {TimeUnit.SECONDS.sleep(t);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("f2="+t);return t;});f1.runAfterEither(f2, ()->{System.out.println("上面有一个已经完成了。");}).get();}

 

runAfterBoth

两个CompletionStage,都完成了计算才会执行下一步的操作

public CompletionStage<Void> runAfterBoth(CompletionStage<?> other,Runnable action);
public CompletionStage<Void> runAfterBothAsync(CompletionStage<?> other,Runnable action);
public CompletionStage<Void> runAfterBothAsync(CompletionStage<?> other,Runnable action,Executor executor);
	private static void runAfterBoth() throws Exception {CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic 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<Integer> f2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic 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;}});f1.runAfterBoth(f2, new Runnable() {@Overridepublic void run() {System.out.println("上面两个任务都执行完成了。");}}).get();}private static void runAfterBoth2() throws Exception {CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(()->{int t = new Random().nextInt(3);try {TimeUnit.SECONDS.sleep(t);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("f1="+t);return t;});CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(()->{int t = new Random().nextInt(3);try {TimeUnit.SECONDS.sleep(t);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("f2="+t);return t;});f1.runAfterBoth(f2, ()->{System.out.println("上面两个任务都执行完成了。");}).get();}

 8.complete

runAsync 执行完成则以该结果为准;如果未执行完成时执行complete,则返回complete值

	public static void complete() throws Exception {CompletableFuture<Integer> runAsync = CompletableFuture.supplyAsync(()->{try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("run end ...");return 1;});TimeUnit.SECONDS.sleep(2);// runAsync 执行完成则以该结果为准;如果未执行完成时执行complete,则返回complete值runAsync.complete(-1);System.out.println("success:"+ runAsync.get());}

 

9.allOf 多实例同时返回 、anyOf 多实例一个执行完成返回

allOf

在这里我们可以将对各future实例添加到allOf方法中,然后通过future的get()方法获取future的状态。如果allOf里面的所有线程为执行完毕,主线程会阻塞,直到allOf里面的所有线程都执行,线程就会被唤醒。

		CompletableFuture<String> future1 = CompletableFuture.supplyAsync(new Supplier<String>() {@Overridepublic String get() {try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}return "hello";}});CompletableFuture<String> future2 = CompletableFuture.supplyAsync(new Supplier<String>() {@Overridepublic String get() {return "world";}});CompletableFuture<String> future3 = CompletableFuture.supplyAsync(new Supplier<String>() {@Overridepublic String get() {try {TimeUnit.SECONDS.sleep(5);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}return "!!!";}});long currentTimeMillis = System.currentTimeMillis();System.out.println(future1.isDone()+" "+future2.isDone()+" "+future3.isDone());CompletableFuture<Void> allOf = CompletableFuture.allOf(future1,future2,future3);allOf.get();//这里会等待三个任务都执行完成System.out.println("执行完成,时间:"+(System.currentTimeMillis()-currentTimeMillis));System.out.println(future1.isDone()+" "+future2.isDone()+" "+future3.isDone());


anyOf

调用方法与allOf基本相同,区别在于anyOf是,其中一个执行完成则往下执行

anyOf get()方法返回最先执行完的Future

		CompletableFuture<String> future1 = CompletableFuture.supplyAsync(new Supplier<String>() {@Overridepublic String get() {try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}return "hello";}});CompletableFuture<String> future2 = CompletableFuture.supplyAsync(new Supplier<String>() {@Overridepublic String get() {try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}return "world";}});CompletableFuture<String> future3 = CompletableFuture.supplyAsync(new Supplier<String>() {@Overridepublic String get() {try {TimeUnit.SECONDS.sleep(5);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}return "!!!";}});long currentTimeMillis = System.currentTimeMillis();System.out.println(future1.isDone()+" "+future2.isDone()+" "+future3.isDone());//		CompletableFuture<Void> allOf = CompletableFuture.allOf(future1,future2,future3);//		allOf.thenAccept((x)->{//			System.out.println("123:"+x);//		}).get();CompletableFuture<Object> anyOf = CompletableFuture.anyOf(future1,future2,future3);System.out.println("结果:"+anyOf.get());System.out.println("执行完成,时间:"+(System.currentTimeMillis()-currentTimeMillis));System.out.println(future1.isDone()+" "+future2.isDone()+" "+future3.isDone());

 

 

10.所有方法 Async 与 非Async 区别

比如:thenApply与thenApplyAsync 等等

参考:https://blog.csdn.net/leon_wzm/article/details/80560081

public static void main(String[] args) throws Exception {async1();async2();async3();}public static void async1() throws Exception {CompletableFuture<String> future1 = CompletableFuture.supplyAsync(()->{try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("supplyAsync:"+Thread.currentThread().getName() +" "+Thread.currentThread().getId());return "hello";});TimeUnit.SECONDS.sleep(5);CompletableFuture<Integer> thenApply = future1.thenApply((x)->{System.out.println("thenApply:"+Thread.currentThread().getName() +" "+Thread.currentThread().getId());return 1;});thenApply.get();}public static void async2() throws Exception {CompletableFuture<String> future1 = CompletableFuture.supplyAsync(()->{try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("supplyAsync:"+Thread.currentThread().getName() +" "+Thread.currentThread().getId());return "hello";});CompletableFuture<Integer> thenApply = future1.thenApply((x)->{System.out.println("thenApply:"+Thread.currentThread().getName() +" "+Thread.currentThread().getId());return 1;});thenApply.get();}public static void async3() throws Exception {CompletableFuture<String> future1 = CompletableFuture.supplyAsync(()->{try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("supplyAsync:"+Thread.currentThread().getName() +" "+Thread.currentThread().getId());return "hello";});TimeUnit.SECONDS.sleep(5);CompletableFuture<Integer> thenApply = future1.thenApplyAsync((x)->{System.out.println("thenApply:"+Thread.currentThread().getName() +" "+Thread.currentThread().getId());return 1;});thenApply.get();}

 

 

 

 

 

 

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/509797.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Java 8 CompletableFuture 教程

Java 8 有大量的新特性和增强如 Lambda 表达式&#xff0c;Streams&#xff0c;CompletableFuture等。在本篇文章中我将详细解释清楚CompletableFuture以及它所有方法的使用。 什么是CompletableFuture&#xff1f; 在Java中CompletableFuture用于异步编程&#xff0c;异步编…

Dubbo 2.7.x admin 控制台管理提示 : 无元数据信息,请升级至Dubbo2.7及以上版本

版本&#xff1a;2.7.3 安装完Dubbo admin 运行后&#xff0c;查询服务提示 无元数据信息&#xff0c;请升级至Dubbo2.7及以上版本&#xff0c;或者查看application.properties中关于config center的配置&#xff0c;详见 这里 这里描述着处理方法&#xff1a;https://github…

Unity在运行时(代码中)设置材质的渲染模式(RenderingMode)

在Unity中&#xff0c;有些少数情况下我们需要用代码来创建材质。比如说在材质非常多&#xff0c;而仅仅是纹理不一样的时候。 而用代码创建的材质是没有对应的资源文件的&#xff0c;我们也就无法使用Inspector来设置它的Rendering Mode。 关于Rendering Mode&#xff0c;许我…

java中String与new String的区别

String类&#xff1a;表示不可改变的字符串&#xff0c;当前对象创建完毕之后&#xff0c;该对象的内容&#xff08;字符序列&#xff09;是不能改变的&#xff0c;一旦内容改变就是一个新的对象。 String对象的创建&#xff1a; 1&#xff09;&#xff1a;直接赋一个字面量&a…

Yarn 监控 - 监控任务运行状态 (包括Spark,MR 所有在Yarn中运行的任务)

目录 Maven pom引用 配置文件 代码 平时开发中可以在yarn的web页面查看应用程序运行状态&#xff0c;如下图 下面代码实现了&#xff0c;代码监控Yarn运行程序&#xff0c;可以对部分任务进行实时监控 Maven pom引用 这里Demo使用的hadoop版本是 3.0.0 <dependency>…

Behavior Designer

https://my.oschina.net/acitiviti/blog/621627

java中常用的String方法

package com.test;import java.io.Console; import java.util.Arrays; import java.util.Scanner;public class Main {public static void main(String[] agrs){char[] cs new char[]{A, b, c};String str1 new String(cs);System.out.println("-------------变成哈希值…

HugeGraph 图数据库索引介绍 - 范围索引,全文索引

目录 HugeGraph 索引介绍 二级索引 组合索引 范围索引 全文索引 HugeGraph 索引介绍 二级索引 创建schema和添加数据 schema.propertyKey("name").asText().ifNotExist().create();schema.propertyKey("uid").asLong().ifNotExist().create();schem…

谷歌c++风格摘抄

全部来源于网络&#xff0c;我感觉好的就复制粘贴了。【你必需防止头文件重复编译。】<PROJECT>_<PATH>_<FILE>_H_foo/src/bar/baz.h > #ifndef FOO_BAR_BAZ_H_【inline函数要尽量简单。】函数最好小于10行。函数内包含循环、switch语句&#xff0c;不能定…

HugeGraph 图数据库常见问题汇总

索引介绍&#xff1a;https://blog.csdn.net/it1993/article/details/89492296 分词问题&#xff1a;https://github.com/hugegraph/hugegraph/issues/779 Hugegraph是否支持外部索引&#xff1a;https://github.com/hugegraph/hugegraph/issues/542 Hugegraph二级索引进行模…

String练习代码保存

package com.test;public class M1001{public static void main(String[] args) {System.out.println("-----------字符串截取----------------");String str "a,b,c,d,e,,";String[] str1 null;str1str.split(",");for(String st : str1){Sys…

Hbase JMX 监控 - Region

获取Region监控信息页面&#xff1a; http://regionServerName:16030/jmx?qryHadoop:serviceHBase,nameRegionServer,subRegions 获得数据如下 参数代表含义 *** 为前缀代表&#xff1a;Namespace_${namespace}_table_${tableName}_region_${regionName} ***_metric_storeCo…

String、StringBuilder和StringBuffer的区别和用法

分别使用使用这三种来拼接字符串&#xff0c;对比各自损耗的时间&#xff1a; 经过测试&#xff1a; package com.test;public class Main{public static void main(String[] args){testString();testStringBuffer();testStringBuilder();}private static void testStringBui…

Hbase Compaction 源码分析 - CompactionChecker

其他相关文章 Hbase Compaction 源码分析 - CompactionChecker Hbase Compaction 源码分析 - RatioBasedCompactionPolicy 策略 Hbase Compaction 源码分析 - CompactSplitThread 线程池选择 CompactionChecker 介绍&#xff1a; RegionServer会在后台启动一个线程Compac…

c++ 之类的前置声明

转自&#xff1a;http://blog.csdn.net/fjb2080/archive/2010/04/27/5533514.aspx 作者&#xff1a;清林&#xff0c;博客名&#xff1a;飞空静渡 刚开始学习c的人都会遇到这样的问题&#xff1a; 定义一个类 class A&#xff0c;这个类里面使用了类B的对象b&#xff0c;然后定…

java中随机数Random和ThreadLocalRandom()用法与区别

package com.test;import java.util.Random; import java.util.concurrent.ThreadLocalRandom;public class M1001{public static void main(String[] args) {Random random new Random();System.out.println("-----------产生1到10之间的随机数----------------");…

Hbase Compaction 源码分析 - RatioBasedCompactionPolicy 策略

目录 类的关系图 ​ RatioBasedCompactionPolicy selectCompaction 方法 getCurrentEligibleFiles方法 skipLargeFiles方法 createCompactionRequest方法 filterBulk方法 applyCompactionPolicy方法 removeExcessFiles方法 setIsMajor方法 其他相关文章 Hbase Compa…

Hbase Compaction 源码分析 - CompactSplitThread 线程池选择

目录 CompactSplitThread requestCompactionInternal方法 selectCompaction方法 requestCompaction方法 其他相关文章 Hbase Compaction 源码分析 - CompactionChecker Hbase Compaction 源码分析 - RatioBasedCompactionPolicy 策略 Hbase Compaction 源码分析 - CompactS…

java如何生成验证码

package com.test;import java.util.Random; import java.util.UUID; import java.util.concurrent.ThreadLocalRandom;public class M1001{public static void main(String[] args) {System.out.println("-----------产生5个随机数的验证码----------------");Strin…

m3u8下载ts 合并成一个视频

我们在用网页看视频时&#xff0c;很多时候视频是下载不下来的&#xff0c;当然这里面有很多技术来防止我们下载视频&#xff0c;接下来我将破解使用m3u8格式来下载视频。一般情况下&#xff0c;我们使用浏览器中Network来查看服务器和本机的数据传输&#xff0c;而视频的原地址…