通过单例枚举类创建线程池的应用

66 阅读1分钟

在项目开发中经常需要提高并发线程数来优化性能,或者通过异步线程来提高应用的吞吐,在使用线程的过程中,线程池的使用必不可少,可是该如何使用好线程池呢?以下是自己在实际项目中使用线程池的一个案例,如有更好的使用方式,欢迎一同探讨。

线程池作为一个公用的类,应当设计为单例模式,这是利用枚举类来实现单例的一个应用

public enum EnumCreateThreadPool {
    threadPoolInstance;

    private static ThreadPoolExecutor tpe;

	// 静态代码块,项目初始化时将线程池一并初始化好,对于一些变量可以通过配置文件来获取
    static {
        tpe = new ThreadPoolExecutor(
                10,
                10,
                0,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(1000),
                //自己实现ThreadFactory,给线程起好name,方便排查问题
                new ThreadFactoryImpl("just_test_"),
                //拒绝策略,个人认为处理不了就抛异常或通过MQ做异步,等空闲在处理,具体看业务逻辑需要
                new ThreadPoolExecutor.AbortPolicy()
        );
    }
    //使用submit还是execute请参考这篇文章   https://juejin.cn/post/7350917259718574107

    public Future<?> submit(Runnable runnable) {
        return tpe.submit(runnable);
    }

    public void execute(Runnable runnable) {
        tpe.execute(runnable);
    }
}
class ThreadFactoryImpl implements ThreadFactory {
    private final AtomicLong threadIndex = new AtomicLong(0);
    private final String threadNamePrefix;
    private final boolean daemon;

    public ThreadFactoryImpl(final String threadNamePrefix) {
        this(threadNamePrefix, false);
    }

    public ThreadFactoryImpl(final String threadNamePrefix, boolean daemon) {
        this.threadNamePrefix = threadNamePrefix;
        this.daemon = daemon;
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(r, threadNamePrefix + this.threadIndex.incrementAndGet());
        thread.setDaemon(daemon);
        return thread;
    }
}

class TestPool {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Future<?> submit = EnumCreateThreadPool.threadPoolInstance.submit(() -> {
            //线程要跑的任务
        });
    }
}