CompletableFuture是java8提供的异步任务创建,回调,编排和异常处理.
创建异步任务
1. runAsync(Runnable runnable),创建一个没有返回值的异步任务,接受一个Runnable接口的实现类对象.
static CompletableFuture<Void> runAsync(Runnable runnable)
示例,异步读取指定文件
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(5);
CommonUtil.printThreadLog("start");
CompletableFuture.runAsync(() -> {
CommonUtil.printThreadLog("读取文件");
String news = CommonUtil.readFile("news.txt");
CommonUtil.printThreadLog(news);
CommonUtil.printThreadLog("读取文件结束");
},executor);
//关闭线程池
executor.shutdown();
CommonUtil.printThreadLog("end");
2. supplyAsync(Supplier supplier),创建一个有返回值的异步任务
static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
示例
ExecutorService executor = Executors.newFixedThreadPool(5);
CommonUtil.printThreadLog("start");
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
CommonUtil.printThreadLog("读取文件");
String news = CommonUtil.readFile("news.txt");
CommonUtil.printThreadLog("读取文件结束");
return news;
},executor);
CommonUtil.printThreadLog(future.get());
//关闭线程池
executor.shutdown();
CommonUtil.printThreadLog("end");
示例中使用到的CommonUtil
public class CommonUtil {
/**
* 读取指定路径的文件
* @param pathFile
* @return
*/
public static String readFile(String pathFile){
try {
pathFile = "D:\\study\\zlm_platform\\src\\main\\resources\\"+pathFile;
return Files.readString(Paths.get(pathFile));
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
/**
* 休眠指定毫秒数
* @param millis
*/
public static void sleepMillis(long millis){
try {
TimeUnit.MILLISECONDS.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 休眠指定秒数
* @param seconds
*/
public static void sleepSecond(int seconds){
try {
TimeUnit.SECONDS.sleep(seconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 答应输出带线程信息的日志
* @param message
*/
public static void printThreadLog(String message){
String result = new StringJoiner(" | ")
.add(String.valueOf(System.currentTimeMillis()))
.add(String.format("%2d",Thread.currentThread().getId()))
.add(String.valueOf(Thread.currentThread().getName()))
.add(message)
.toString();
System.out.println(result);
}
}