线程池的几种使用方式

方式一

    <bean id="taskExecutor" name="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
          <!-- 核心线程数,默认为1 -->  
        <property name="corePoolSize" value="10"></property>  
        <!-- 最大线程数,默认为Integer.MAX_VALUE -->  
        <property name="maxPoolSize" value="50"></property>
        <!-- 队列最大长度,一般需要设置值>=notifyScheduledMainExecutor.maxNum;默认为Integer.MAX_VALUE-->  
        <property name="queueCapacity" value="1000"></property>
        <!-- 线程池维护线程所允许的空闲时间,默认为60s -->  
        <property name="keepAliveSeconds" value="60"></property> 
    </bean> 

//线程调用

   @Resource(name = "taskExecutor")
     private ThreadPoolTaskExecutor taskExecutor;
     。。。。
     方法内部:
    UploadTransWordThread wordThread = new UploadTransWordThread(imgPaths,inputFile, htmlPath, imgsUrl);
     taskExecutor.execute(wordThread);
public class UploadTransWordThread implements Runnable {
	private String inputFile="";
	private String imgPaths="";
	private String htmlPath="";
	private String imgUrl="";
	
	public UploadTransWordThread(String imgPaths, String inputFile,
			String htmlPath,String imgUrl) {
		super();
		this.inputFile = inputFile;
		this.imgPaths = imgPaths;
		this.htmlPath = htmlPath;
		this.imgUrl = imgUrl;
	}

	@Override
	public void run() {
		
		try {
			WordtoHtml.wordTohtml(imgPaths,inputFile, htmlPath,imgUrl);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
		}
		
	}

}

方式二 springboot中1

@Configuration
@EnableAsync//开启异步注解
public class ThreadPoolConfig
{
    // 核心线程池大小
    private int corePoolSize = 50;
    // 最大可创建的线程数
    private int maxPoolSize = 200;
    // 队列最大长度
    private int queueCapacity = 1000;
    // 线程池维护线程所允许的空闲时间
    private int keepAliveSeconds = 300;
    @Bean(name = "threadPoolTaskExecutor")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor()
    {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setMaxPoolSize(maxPoolSize);
        executor.setCorePoolSize(corePoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        // 线程池对拒绝任务(无线程可用)的处理策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }
    }

调用方式:

 @Async("threadPoolTaskExecutor")
 public List findTwoDiabetesFollow(){
 ......
}

方式三 延迟调用的线程池,用于日志打印

配置线程池,参数同方法二

    /**
     * 执行周期性或定时任务
     */
    @Bean(name = "scheduledExecutorService")
    protected ScheduledExecutorService scheduledExecutorService()
    {
        return new ScheduledThreadPoolExecutor(corePoolSize,
                new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build())
        {
            @Override
            protected void afterExecute(Runnable r, Throwable t)
            {
                super.afterExecute(r, t);
                Threads.printException(r, t);
            }
        };
    }

延迟执行设置

public class AsyncManager
{
    /**
     * 操作延迟10毫秒
     */
    private final int OPERATE_DELAY_TIME = 10;

    /**
     * 异步操作任务调度线程池
     */
    private ScheduledExecutorService executor = SpringUtils.getBean("scheduledExecutorService");

    /**
     * 单例模式
     */
    private AsyncManager(){}

    private static AsyncManager me = new AsyncManager();

    public static AsyncManager me()
    {
        return me;
    }

    /**
     * 执行任务
     * 
     * @param task 任务
     */
    public void execute(TimerTask task)
    {
        executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
    }

    /**
     * 停止任务线程池
     */
    public void shutdown()
    {
        Threads.shutdownAndAwaitTermination(executor);
    }
}

调用方式

AsyncManager.me().execute(AsyncFactory.recordOper(operLog));
。。。。
   public static TimerTask recordOper(final SysOperLog operLog)
    {
        return new TimerTask()
        {
            @Override
            public void run()
            {
                // 业务方法执行
               operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp()));
                SpringUtils.getBean(ISysOperLogService.class).insertOperlog(operLog);
            }
        };
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值