import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author shine
* @version 1.0
* @date 10/11/2022 PM 5:18
*/
public class JavaAsync {
private static volatile ExecutorService executorService;
/*
* Ensures that the ExecutorService is shutdown when the JVM exits.
*/
static {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
if (executorService != null) {
executorService.shutdownNow();
}
}
});
}
/**
* Returns the JavaAsync executor service.
*
* @return the JavaAsync executor service
*/
public static ExecutorService getExecutorService() {
if (JavaAsync.executorService == null) {
synchronized (JavaAsync.class) {
if (JavaAsync.executorService == null) {
JavaAsync.executorService = Executors.newCachedThreadPool();
}
}
}
return JavaAsync.executorService;
}
/**
* Use a custom executor service.
*
* @param executorService executor service to use
*/
public static void setExecutorService(final ExecutorService executorService) {
synchronized (JavaAsync.class) {
JavaAsync.executorService = executorService;
}
}
/**
* description:
* Synchronization Method
*
* @param param
* @return java.lang.String
*/
public static String synchronizationMethod(String param) {
System.out.println("synchronizationMethod " + Thread.currentThread().getName());
return param + " synchronizationMethod";
}
/**
* description:
*
* @param param
* @return java.util.concurrent.CompletableFuture<java.lang.String>
*/
public static CompletableFuture<String> asynchronousMethods(String param) {
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> synchronizationMethod(param), JavaAsync.getExecutorService());
System.out.println("asynchronousMethods " + Thread.currentThread().getName());
return completableFuture;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
String param = "param";
synchronizationMethod(param);
CompletableFuture<String> stringCompletableFuture = asynchronousMethods(param);
String returnValue = stringCompletableFuture.get();
System.out.println(returnValue);
}
}
运行结果如下