今天面试突然被问题到java异步操作,恰好最近在看小狂神的JUC教程,不过正好只差这一集没有看到,气得我真想抽自己两巴掌。
先上两个Demo:
无返回值类型:package com.allen.futrue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class FutureDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture completableFuture = CompletableFuture.runAsync(()->{
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "->runAsync");
});
System.out.println("123");
completableFuture.get();
}
}
运行结果:
如上图所见,控制台先输出123,然后是等待睡眠两秒结束后异步输出了线程的名称。
有返回值类型:package com.allen.futrue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class FutureDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture completableFuture = CompletableFuture.supplyAsync(()->{
System.out.println(Thread.currentThread().getName() + "->runAsync");
//制造异常System.out.println(1 / 0);
return 200;
});
completableFuture.whenComplete((t, u)->{
System.out.println("t->" + t);
System.out.println("u->" + u);
}).exceptionally((e)->{
System.out.println(e.getMessage());
return 500;
});
}
}
没有异常正常返回:
我们得到结论:t为return的值。
当有了异常的情况:
t返回null,u为异常信息。
同时Futrue也会执行exceptionally里面的代码。