Java thread pool and singleton mode

1. Thread pool architecture

Executor is the root interface responsible for the use and scheduling of threads
|–ExecutorService interface: the main interface of the thread pool. Added return Future object
|–ThreadPoolExecutor thread pool implementation class
|–ScheduledExceutorService interface: responsible for thread scheduling
|–ScheduledThreadPoolExecutor: inherits ThreadPoolExecutor and implements ScheduledExecutorService

2. Singleton mode definition

A simple understanding is that a class can only have one instance, and only one instance will be created when the thread pool is in use

3. Hungry-style thread pool execution factory

import cn.hutool.core.thread.NamedThreadFactory;
import lombok.NonNull;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 描述:饿汉式 线程池执行器工厂.
 * 1.单例
 * 2.不管有没有调用者都会提前创建实例,资源利用效率低
 */
public final class HungryThreadPoolFactory {
    
    

    private HungryThreadPoolFactory() {
    
    
    }

    /**
     * 全局访问点.
     * @param runnable runnable
     */
    public static void execute(@NonNull Runnable runnable) {
    
    
        getInstance().execute(runnable);
    }

    /**
     * 静态公用工厂方法,返回唯一实例.
     * @return ThreadPoolExecutor
     */
    public static ThreadPoolExecutor getInstance() {
    
    
        return HungryThreadPoolFactory.THREAD_POOL_EXECUTOR;
    }

    static final int CPU = Runtime.getRuntime().availableProcessors();
    static final int CORE_POOL_SIZE = CPU + 1;
    static final int MAXIMUM_POOL_SIZE = CPU * 2 + 1;
    static final long KEEP_ALIVE_TIME = 1L;
    static final TimeUnit TIME_UNIT = TimeUnit.SECONDS;
    static final int MAX_QUEUE_NUM = 1024;

    /**
     * 静态私有成员变量.
     */
    private static ThreadPoolExecutor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(
            CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, TIME_UNIT,
            new LinkedBlockingQueue<>(MAX_QUEUE_NUM),
            new NamedThreadFactory("ThreadPoolExecutorFactory-", false),
            new ThreadPoolExecutor.AbortPolicy());
}

4. Lazy thread pool execution factory

import cn.hutool.core.thread.NamedThreadFactory;
import lombok.NonNull;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 描述:懒汉式 线程池执行器工厂.
 * 1.单例
 * 2.延迟加载:解决了饿汉式不管有没有调用都创建实例的弊端。但是多线程访问可能会创建多个实例,所以需要解决线程安全问题
 */
public final class LazyThreadPoolFactory {
    
    

    private LazyThreadPoolFactory() {
    
    
    }

    /**
     * 全局访问点.
     * @param runnable runnable
     */
    public static void execute(@NonNull Runnable runnable) {
    
    
        getInstance().execute(runnable);
    }

    /**
     * 静态私有成员变量.
     */
    private static ThreadPoolExecutor THREAD_POOL_EXECUTOR = null;

    public static ThreadPoolExecutor getInstance() {
    
    
        generateInstance();
        return LazyThreadPoolFactory.THREAD_POOL_EXECUTOR;
    }

    static final int CPU = Runtime.getRuntime().availableProcessors();
    static final int CORE_POOL_SIZE = CPU + 1;
    static final int MAXIMUM_POOL_SIZE = CPU * 2 + 1;
    static final long KEEP_ALIVE_TIME = 1L;
    static final TimeUnit TIME_UNIT = TimeUnit.SECONDS;
    static final int MAX_QUEUE_NUM = 1024;

    public static void generateInstance() {
    
    
        //校验实例是否已生成,避免多线程访问重复生成实例
        if (THREAD_POOL_EXECUTOR == null) {
    
    
            THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(
                    CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, TIME_UNIT,
                    new LinkedBlockingQueue<>(MAX_QUEUE_NUM),
                    new NamedThreadFactory("ThreadPoolExecutorFactory-", false),
                    new ThreadPoolExecutor.AbortPolicy());
        }
    }
}

5. Static inner class implements thread pool factory (a method used in development)

import cn.hutool.core.thread.NamedThreadFactory;
import lombok.NonNull;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 描述:静态内部类 线程池执行器工厂.
 * 1.单例
 * 2.饿汉式+延迟加载
 * @author wangkai
 */
public final class SafeThreadPoolFactory {
    
    

    private SafeThreadPoolFactory() {
    
    
    }

    /**
     * 全局访问点.
     * @param runnable runnable
     */
    public static void execute(@NonNull Runnable runnable) {
    
    
        ThreadPoolExecutorHolder.THREAD_POOL_EXECUTOR.execute(runnable);
    }

    /**
     * 静态内部类创建实例(单例).
     * 优点:被调用时才会创建一次实例
     */
    private static class ThreadPoolExecutorHolder {
    
    
        static final int CPU = Runtime.getRuntime().availableProcessors();
        static final int CORE_POOL_SIZE = CPU + 1;
        static final int MAXIMUM_POOL_SIZE = CPU * 2 + 1;
        static final long KEEP_ALIVE_TIME = 1L;
        static final TimeUnit TIME_UNIT = TimeUnit.SECONDS;
        static final int MAX_QUEUE_NUM = 1024;

        //static变量只会初始化一次
        public static final ThreadPoolExecutor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(
                CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, TIME_UNIT,
                new LinkedBlockingQueue<>(MAX_QUEUE_NUM),
                new NamedThreadFactory("ThreadPoolExecutorFactory-", false),
                new ThreadPoolExecutor.AbortPolicy());
    }
}

Guess you like

Origin blog.csdn.net/qq_44732146/article/details/129023655