JAVA编码(41)—— 线程池队列执行任务(ThreadPoolQueue)(1)
废话少说,上代码
package com.sinosoft; import java.util.concurrent.*; /** * Created by xushuyi on 2017/4/9. */ public class ThreadPoolQueue { /** * 定义线程池中最大的线程数量 */ private static final Integer THREADPOOLSIZE = 100; /** * 创建线程队列 */ private static final BlockingQueue<Object[]> QUEUE = new LinkedBlockingQueue<Object[]>(); /** * 创建线程池 */ protected static ExecutorService executorService = Executors.newFixedThreadPool(THREADPOOLSIZE); /** * 线程池任务调度执行 */ static { executorService.execute(new Runnable() { public void run() { while (!Thread.currentThread().isInterrupted()) { Object[] task = null; try { task = QUEUE.take(); } catch (Exception e) { e.printStackTrace(); } System.out.println("执行任务结果:" + task[0]); } } }); } /** * 线程池中添加执行任务 * * @param task t */ public void newTaskToThreadPool(Object[] task) { QUEUE.offer(task); } public static void main(String[] args) { ThreadPoolQueue queue = new ThreadPoolQueue(); Object[] task = null; for (int i = 0; i < 10; i++) { task = new Object[]{"xushuyi_" + i}; queue.newTaskToThreadPool(task); } } }
真正项目中,就不会再使用static来初始化任务,而是定义一个方法,比如:public void runnbaleInit(),那么在配置文件中需要将本方法注入到Bean中
例如:
<bean id="policyMicroProductServiceSpringImpl" class="com.sinosoft.wechatscreen.service.impl.PolicyMicroProductServiceSpringImpl" init-method="runnbaleInit"></bean>

浙公网安备 33010602011771号