线程池规范创建模板

1.创建一个线程工厂 MyThreadFactory

package cn.gdxiash.consumer.thread.factory;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author ShangHai
 * @desc
 */
public class MyThreadFactory implements ThreadFactory{

    private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1);
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    public MyThreadFactory() {
        this("shangHaiPool-");
    }

    public MyThreadFactory(String name){
        SecurityManager securityManager = System.getSecurityManager();
        group = (securityManager != null) ? securityManager.getThreadGroup() : Thread.currentThread().getThreadGroup();
        // 此时namePrefix就是 name + 第几个用这个工厂创建线程池的
        this.namePrefix = name + POOL_NUMBER.getAndIncrement();
    }

    @Override
    public Thread newThread(Runnable r) {
        //此时线程的名字 就是 namePrefix + -thread- + 这个线程池中第几个执行的线程
        Thread t = new Thread(group, r, namePrefix + "-thread-"+threadNumber.getAndIncrement(), 0);
        if (t.isDaemon()) {
            t.setDaemon(false);
        }
        if (t.getPriority() != Thread.NORM_PRIORITY) {
            t.setPriority(Thread.NORM_PRIORITY);
        }
        return t;
    }

}

2.创建线程池参数配置文件 threadPool.properties

thread.pool.corePoolSize=8
thread.pool.maxPoolSize=16
thread.pool.keepAliveSeconds=180
thread.pool.queueCapacity=10
thread.pool.threadFactoryName=shangHaiPool-

3.创建一个线程池工具类  ThreadPoolUtil

package cn.gdxiash.consumer.utils;

import cn.gdxiash.consumer.thread.factory.MyThreadFactory;

import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.*;

/**
 * @author ShangHai
 * @desc
 */
public class ThreadPoolUtil {

    private static ExecutorService executorService;

    static {
        // 初始化加载
        initExecuteService();
    }

    private static void initExecuteService(){
        try{
            Properties properties = new Properties();
            properties.load(ThreadPoolUtil.class.getClassLoader().getResourceAsStream("threadPool.properties"));
            if(properties == null){
                throw new RuntimeException("threadPool参数读取异常:配置文件无法加载");
            }
//            int corePoolSize = Integer.parseInt((String)properties.get("thread.pool.corePoolSize"));
//            int maxPoolSize = Integer.parseInt((String)properties.get("thread.pool.maxPoolSize"));
            // 直接获取本机线程核心数
            int corePoolSize = Runtime.getRuntime().availableProcessors();
            int maxPoolSize = 2*corePoolSize;
            // 非核心线程最大空闲生存时间
            long keepAliveSeconds = Long.parseLong((String)properties.get("thread.pool.keepAliveSeconds"));
            // 队列最大容量
            int queueCapacity = Integer.parseInt((String)properties.get("thread.pool.queueCapacity"));
            String threadFactoryName = (String)properties.get("thread.pool.threadFactoryName");

            // 线程池创建
            executorService = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveSeconds, TimeUnit.SECONDS,
                    new ArrayBlockingQueue<Runnable>(queueCapacity), new MyThreadFactory(threadFactoryName));
        } catch(IOException var1) {
            throw new RuntimeException("threadPool参数读取异常:加载配置文件threadPool.properties失败", var1);
        }
    }

    public static ExecutorService getExecutorService() {
        if(executorService == null){
            initExecuteService();
        }
        return executorService;
    }

    public static void setExecutorService(ExecutorService executorService) {
        ThreadPoolUtil.executorService = executorService;
    }
}

4.在需要使用到线程的地方,引用它即可

ExecutorService executorService = ThreadPoolUtil.getExecutorService();

demo

package cn.gdxiash.consumer.thread;

import cn.gdxiash.consumer.utils.ListUtil;
import cn.gdxiash.consumer.utils.ThreadPoolUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author ShangHai
 * @desc
 */
public class Exam02 {

    public static void main(String[] args) {
        List<String> dataList = new ArrayList<>();
        dataList.add("A");
        dataList.add("B");
        dataList.add("C");
        dataList.add("D");
        dataList.add("E");
        dataList.add("F");
        dataList.add("G");
        dataList.add("H");
        dataList.add("I");
        dataList.add("J");
        Exam02.testLatch(dataList);
    }

    private static void testLatch(List<String> dataList){
        if(dataList==null || dataList.isEmpty()){
            return;
        }

        // CPU核心数   分隔后,分隔后集合的数量
        int cpuNumber = Runtime.getRuntime().availableProcessors();

        if(dataList.size() < cpuNumber){
            cpuNumber = dataList.size();
        }

        // 使用自定义线程池
        ExecutorService executorService = ThreadPoolUtil.getExecutorService();

        CountDownLatch latch = new CountDownLatch(cpuNumber);
        // 将集合平均分成cpuNumber个
        List<List<String>> dataLists = ListUtil.averageAssign(dataList, cpuNumber);

        for(int i=0;i<cpuNumber;i++){
            final int INDEX = i;
            executorService.execute(()->{
                try{
                    List<String> executeList = dataLists.get(INDEX);
                    for(String execute:executeList){
                        System.out.print("【"+Thread.currentThread().getName() + "】元素:"+execute +" || ");
                    }
                    System.out.println("\n--------------------");
                } catch(Exception e) {
                    e.printStackTrace();
                } finally {
                    latch.countDown();
                }
            });
        }

        try {
            System.out.println("主线程陷入等待");
            latch.await();
            System.out.println("主线程继续执行");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 程序停止,杀死线程池
            ThreadPoolUtil.getExecutorService().shutdown();
        }

    }

}

执行main方法,输出结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值