线程池在项目中的实战

线程池的原理和作用相比大家都比较了解了,不熟悉的可以看这篇文章
链接: 线程池的使用(点击查看).

一个项目中要求对丢MQ队列的消息用线程池接收处理,直接贴代码
配置线程池的类

/**
 * 线程池配置
 */
@Configuration
public class ThreadPoolConfig {
    //200个线程
    public static final int THREADNUM = 200;
    //日志
    private static final Logger logger = LoggerFactory.getLogger(ThreadPoolConfig.class);
    /**
     * 支付宝账单处理
     */
    @Bean(name = "testPool",
            destroyMethod = "shutdown")
    public ExecutorService testPool() {
        ExecutorService pool = new ThreadPoolExecutor(THREADNUM, THREADNUM, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(1024),
                new ThreadFactoryBuilder().setNameFormat("test-pool-%d").build(), new ThreadPoolExecutor.AbortPolicy());

        logger.info("ExecutorService {} has been crerated", "testPool");
        return pool;
    }
}

这是业务处理

@Service
public class TestThread {
     //日志
    private final static Logger logger = LoggerFactory.getLogger(TestThread .class);
    //配置注解进来
    @Autowired
    private ExecutorService testPool;//要和ThreadPoolConfig 中的一致
    //原子操作
    private static AtomicInteger dealCnt = new AtomicInteger(0);
    //把多条遍历去一条条执行,我这里是个List<String>
    public void test(List<String> more) {
        for (String one: lists) {
            dealCnt.incrementAndGet();
            TestSThreads testThreads = new TestSThreads (one, dealCnt);
            testPool.execute(testThreads );
            while (true) {
                if (dealCnt.get() >= ThreadPoolConfig.THREADNUM) {
                    try {
                        Thread.sleep(500 * 1);
                    } catch (InterruptedException e) {
                        logger.debug("nothing");
                    }
                } else {
                    break;
                }
            }
        }
    }
    private class TestSThreads implements Runnable {
        private String one;

        private AtomicInteger dealCnt;

        public TestSThreads (String one, AtomicInteger dealCnt) {
            this.one= one;
            this.dealCnt = dealCnt;
        }
         //在这里直接处理业务
        @SuppressWarnings("unchecked")
        @Override
        public void run() {
         try {
         //业务
          } catch (FileNotFoundException e) {
                logger.error("error",e);
          } finally {
                dealCnt.decrementAndGet();
            }
        }
     }
}

那这里我们就搞定了对多笔业务的线程池分发处理

发布了15 篇原创文章 · 获赞 8 · 访问量 6038

猜你喜欢

转载自blog.csdn.net/Charles_lxx/article/details/101286651