异步(我的理解):
1:有多个线程同时执行,一个线程执行(main)当执行到一个地方,与此同时另一个线程开始执行,两者同一时刻都在运行,最后main线程把其他线程得结果返回。如果需要一个线程等待另一个线程执行完成可以使用CountDownLatch。
2:有多个线程同时执行,一个线程执行(main),先把需要异步执行得代码跳过直接执行后面得代码不会等待其他线程执行完,于此同时其他线程也在执行需要异步的代码。
第一种例子:
public class DataController {
public static void main(String[] args) {
try {
st();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
public static void st() throws Throwable, ExecutionException {
// 两个线程的线程池
ExecutorService executor = Executors.newFixedThreadPool(2);
//jdk1.8之前的实现方式
CompletableFuture future = CompletableFuture.supplyAsync(new Supplier() {
@Override
public String get() {
System.out.println("task started!"+"--"+Thread.currentThread().getName());
try {
//模拟耗时操作
longTimeMethod();
} catch (Exception e) {
e.printStackTrace();
}
return "task finished!";
}
}, executor);
//采用lambada的实现方式
//future.thenAccept(e -> System.out.println(e + " ok"));
future.thenAccept(a-> System.out.println(a+"hhaha"+Thread.currentThread().getName()));
System.out.println("main thread is running");
}
public static void longTimeMethod(){
int i = 10;
try {
Thread.sleep(60000);
while (i > 7){
i--;
System.out.println("脸脸big eges"+Thread.currentThread().getName());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
第二种:之前惠生活业务写过之后补充



