jdk8新特性(Lambda表达式)结合spring 线程池,一行代码实现多线程

1.配置spring 线程池

@Configuration
@EnableAsync
@ConfigurationProperties(prefix="threadpool")
public class ExecutePoolConfiguration {

    @Value("${threadpool.core-pool-size}")
    private int corePoolSize;

    @Value("${threadpool.max-pool-size}")
    private int maxPoolSize;

    @Value("${threadpool.queue-capacity}")
    private int queueCapacity;

    @Value("${threadpool.keep-alive-seconds}")
    private int keepAliveSeconds;


    @Bean(name="threadPoolTaskExecutor")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor(){
        ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
        pool.setKeepAliveSeconds(keepAliveSeconds);
        pool.setCorePoolSize(corePoolSize);//核心线程池数
        pool.setMaxPoolSize(maxPoolSize); // 最大线程
        pool.setQueueCapacity(queueCapacity);//队列容量
        pool.setRejectedExecutionHandler(new java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy()); //队列满,线程被拒绝执行策略
        return pool;
    }
}

2.在配置文件里面增加配置

threadpool:
  core-pool-size: 30
  max-pool-size: 40
  queue-capacity: 1000
  keep-alive-seconds: 300

3.实现多线程

@Component
public class Demo {
	
	@Autowired
	private ThreadPoolTaskExecutor threadPoolTaskExecutor;

	
	
	public void test() {
		List<Integer> array = new ArrayList<Integer>();
		for(int i=1;i<1000;i++) {
			array.add(i);
		}
		//把上述1000条数据,分5个线程处理
		averageAssign(array,5).forEach(
				l -> threadPoolTaskExecutor.execute(
						()->l.forEach(
								m ->System.out.println(m
										)
								)
						)
				);						
		
	}

        public  <T> List<List<T>> averageAssign(List<T> source, int n) {
	    List<List<T>> result = new ArrayList<List<T>>();
	    int remainder = source.size() % n;  //(先计算出余数)
	    int number = source.size() / n;  //然后是商
	    int offset = 0;//偏移量
	    for (int i = 0; i < n; i++) {
	        List<T> value = null;
	        if (remainder > 0) {
	            value = source.subList(i * number + offset, (i + 1) * number + offset + 1);
	            remainder--;
	            offset++;
	        } else {
	            value = source.subList(i * number + offset, (i + 1) * number + offset);
	        }
	        result.add(value);
	    }
	    return result;
	}
}

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值