线程池处理异步任务

/**
 * 异步任务线程池 (单例)
 * 用于异步执行任务
 */
public class ThreadPoolSingleton {
    private static final AtomicReference<ThreadPoolSingleton> INSTANCE = new AtomicReference<>();
    private final ExecutorService executor;

    private ThreadPoolSingleton() {
        /*
            考虑到异步场景较少,且通常情况下不会同时触发多个异步任务,因此核心线程数直接设一个固定值
            int corePoolSize = Runtime.getRuntime().availableProcessors() * 2
            executor = Executors.newFixedThreadPool(corePoolSize)
        */
        executor = Executors.newFixedThreadPool(2);
    }

    /**
     * CAS(Compare and Swap)算法实现了线程安全的单例模式
     * 如果compareAndSet()的返回值为true,即设置成功,则返回current;否则继续循环,直到获取到线程池单例
     */
    public static ThreadPoolSingleton getInstance() {
        for (; ; ) {
            ThreadPoolSingleton current = INSTANCE.get();
            if (current != null) {
                return current;
            }
            current = new ThreadPoolSingleton();
            if (INSTANCE.compareAndSet(null, current)) {
                return current;
            }
        }
    }

    public void submitTask(Runnable task) {
        executor.submit(task);
    }

}

调用示例  ThreadPoolSingleton.getInstance().submitTask(() -> asynchronousTask());

posted @ 2023-06-27 15:02  Ashe|||^_^  阅读(87)  评论(0编辑  收藏  举报