無返回值呼叫
import java.util.concurrent.CompletableFuture;
public class TestDemo {
public static void main(String[] args) {
System.out.println("進入主執行緒=============");
CompletableFuture.runAsync(()->getNum());
System.out.println("主執行緒結束=============");
}
public void getNum(){
System.out.println("執行執行緒=============");
}
}
有返回值呼叫
import java.util.concurrent.CompletableFuture;
public class TestDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 無返回值 runAsync() 有返回值 supplyAsync()
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> getNum());
System.out.println(future.get());
}
private static Integer getNum() {
return 5 / 2;
}
}
使用自定義執行緒池
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestDemo {
/**
* 自定義執行緒池
*/
public static ExecutorService service = Executors.newFixedThreadPool(5);
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 無返回值 runAsync() 有返回值 supplyAsync()
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> getNum(),service);
System.out.println(future.get());
}
private static Integer getNum() {
return 5 / 2;
}
}
處理異常
handleAsync
該方法有兩個引數,一種一個是上一步的結果,另一個則是上一步的異常。而且如果出現異常則第一個引數為null,如果沒有異常則第二個引數為null。
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestDemo {
/**
* 自定義執行緒池
*/
public static ExecutorService service = Executors.newFixedThreadPool(5);
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 無返回值 runAsync() 有返回值 supplyAsync()
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> getNum(),service).handleAsync((res, e) -> {
if (res != null) {
return res;
}
if (e != null) {
return 0;
}
return 0;
});
System.out.println(future.get());
}
private static Integer getNum() {
// by zero
return 5 / 0;
}
}
還有其他很多方法,用到的時候可以去了解。