線程池的原理和作用相比大家都比較瞭解了,不熟悉的可以看這篇文章
鏈接: 線程池的使用(點擊查看).
一個項目中要求對丟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();
}
}
}
}
那這裏我們就搞定了對多筆業務的線程池分發處理