java 方法异步执行


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);
    }

}


运行结果如下

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值