ThreadPoolExecutor-自定义线程池拒绝策略

摘要:由于项目中需要进行数据的清洗整理,大概200w条数据,单一线程进行处理速度太慢。所以开线程池进行处理,加上业务处理代码,大概半小时时间执行完毕。

以下是线程池代码,解释都写在注释里了。

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * 线程池
 */
@Component
public class ThreadPool {

    private final static Logger logger = LoggerFactory.getLogger(ThreadPool.class);

    //基于数组的阻塞队列
    private static BlockingQueue blockingQueue = new ArrayBlockingQueue(300);

    //同时运行线程不超过150个,核心线程数150个
    //最大线程数和核心线程数设置为一样时,设置的时间和时间单位不生效
    //最大线程数比核心线程数大时,若有空余线程空闲超过设置的时常会被回收
    private static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(150, 150,1, TimeUnit.MINUTES, blockingQueue, new RejectedExecutionHandler() {
        //自定义拒绝策略,线程任务队列满了的情况下,任务等待入线程队列
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            try {
                executor.getQueue().put(r);
            } catch (InterruptedException e) {
                logger.error("wait input queue error");
            }
        }
    });

    public void addTask(Integer i) {
        threadPoolExecutor.execute(new Runnable() {
            @Override
            public void run() {
                logger.info("当前i的值:"+i);
                logger.info("当前执行任务的线程名字:"+Thread.currentThread().getName());
            }
        });
    }
    
    public static void main(String[] args) {
        ThreadPool threadPool= new ThreadPool();
        for(Integer i = 0;i < 10;i++){
            threadPool.addTask(i);
        }
}

关于demo中使用的ArrayBlockingQueue:可以看看这篇文章讲的很好

你可能感兴趣的:(JAVA)