线程池

1.Executors工具类创建4种线程池的底层就是threadPoolExcutor类创建的,之中有7个重要的参数。
corePoolSize: 核心线程数
maximumPoolSize: 最大线程数 ,必须大于1
keepAliveTime:多余空闲线程的存活时间
unit:keepAliveTime的单位
workQueue :任务队列,被提交但是尚未被执行的任务
threadFactory :线程工厂,创建线程,(一般默认即可)
handler:拒绝策略,,表示当队列满了,并且工作线程大于等于线程池最大线程数量(maximumPoolSize)时如何来拒绝请求执行的runnable的策略。

2.如何设置合理的参数
cpu 密集型N+1
io密集型 2N
3.拒绝策略的4种
*AbortPolicy 直接抛出异常,阻止系统正常运行
*CallerRunsPolicy 回退给调用者
*DiscartPolicy 抛弃任务
*DiscardOldestPolicy:如果执行程序尚未关闭,则位于工作队列头部的任务将被删除,然后重试执行程序(如果再次失败,则重复此过程)

4.四大函数式接口
java.util.function
*Function<T,R> 函数型接口,T为输入参数,R为返回参数
*Priedicate 断定型接口,返回参数为boolean
*Consumer 消费型接口,参数为T,没有返回值
*Supplier 供给型接口, 没有参数,,返回值为T

5.forkJoin

class Mytask extends RecursiveTask<Integer>{
		
		private  final Integer ADJUST_VALUE = 10;
		
		private int begin;
		private int end;
		private int result;
		
	
		public Mytask(int begin ,int end) {
			this.begin=begin;
			this.end=end;
		}
		
		@Override
		protected Integer compute() {
			if((end-begin) <= ADJUST_VALUE) {
				for (int i = begin; i < end; i++) {
					result = result+i;
				}
			}else {
				int middle =(begin+end)/2;
				Mytask mytask = new Mytask(begin, middle);
				Mytask mytask2 = new Mytask(middle+1, end);
				mytask.fork();
				mytask2.fork();
				result=mytask.join()+mytask2.join();
			}
			return result;
		}
	}
public static void main(String[] args) {

		Mytask mytask = new Mytask(0, 100);
		
		ForkJoinPool forkJoinPool = new ForkJoinPool();
		
		ForkJoinTask<Integer> forkJoinTask = forkJoinPool.submit(mytask);
		
		System.out.println(forkJoinTask.get());
		
		forkJoinPool.shutdown();
	}

6.异步回调 CompletableFuture

public static void main(String[] args) throws InterruptedException, ExecutionException {
		SpringApplication.run(DzqdBackendUiApplication.class, args);
		
CompletableFuture<Void> c=CompletableFuture.runAsync(
				()-> System.out.println(Thread.currentThread().getName()+"无返回"));
		c.get();
		
CompletableFuture<Integer> c1=CompletableFuture.supplyAsync(()-> 
			{
				System.out.println(Thread.currentThread().getName()+"有返回");
				return 100;
			});
		c1.whenComplete((t,u) ->{
			System.out.println("***t" + t);
			System.out.println("***u" + u);
		}).exceptionally(f->{
			System.out.println("***exception"+ f.getMessage());
			return 000;
		}).get();
	}

如何正确 t 为返回值,u为null,错误 t 为null ,u为异常信息

package org.vista.mall.backend.Impl;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vista.mall.backend.common.AbstractEopSpiServiceUtil;
import org.vista.mall.backend.hessian.HessianInfUtil;
import org.vista.mall.backend.service.QueryAbilityRecDetailService;
import org.vista.mall.backend.utils.HttpClientUtils;
import org.vista.mall.backend.utils.LoadPropertiesUtils;
import org.vista.mall.backend.utils.SpiExtensionFactoryUtil;
import org.vista.mall.fact.order.vo.FFlagResult;
import org.vista.mall.fact.service.vo.LogBean;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import com.dzqd.spi.extention.factory.SpiExtensionFactory;
import com.dzqd.spi.vo.ResponseInfo;

/**
 * @description 对账明细查询能力
 * @author fangHao
 * @date 2020年9月16日
 */
public class QueryAbilityRecDetailServiceImpl extends AbstractEopSpiServiceUtil
		implements QueryAbilityRecDetailService {

	static Logger log = LoggerFactory.getLogger(QueryAbilityRecDetailServiceImpl.class);
	static final int arsPageSize = 300;

	@Override
	public FFlagResult execute(Object... arg0) {
		List<String> props = new ArrayList<String>();
		props.add("queryRecDetailUrl");
		Map<String, Object> propMap = LoadPropertiesUtils.getPropertiesConfig("/config/backend_url.properties", props);
		String url = (String) propMap.get("queryRecDetailUrl");
		SpiExtensionFactory spiFactory = SpiExtensionFactoryUtil.getSpiExtensionFactory();
		log.info("------------------对账明细查询能力自动执行开始-----------------");
		LogBean logBean = new LogBean();
		FFlagResult fFlagResult = new FFlagResult("对账明细查询");
		logBean.setfInterfaceName(this.getClass().getSimpleName());
		logBean.setfInterfaceBegintime(new Date());
		Map<String, Object> packageParam = getParam(1, 10);
		Map<String, String> headers = new HashMap<String, String>();
		headers.put("Content-Type", "application/json");
		String msg = "";
		try {
			ResponseInfo httpResult = HttpClientUtils.HttpPostClient(url, JSONObject.toJSONString(packageParam),
					headers, null, null, null, true);
			log.info("打包数据出参{}", JSONObject.toJSONString(httpResult));

			if (null != httpResult && 200 == httpResult.getHttpStatusCode()) {
				int code = (int) JSONPath.read(httpResult.getResponseBody(), "$.code");
				int summary = (int) JSONPath.read(httpResult.getResponseBody(), "$.summary");
				// int summary = 1050;
				if (code == 0 && summary != 0) {
					// 创建一个线程池
					ExecutorService pool = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MILLISECONDS,
							new ArrayBlockingQueue<Runnable>(1), new ThreadPoolExecutor.CallerRunsPolicy());
					// 对账接口并发访问的时候出现数据问题,访问接口的时候加锁
					Lock lock = new ReentrantLock();
					// 创建多个有返回值的任务
					List<Future<Integer>> list = new ArrayList<Future<Integer>>();
					
					int num = summary % arsPageSize == 0 ? summary / arsPageSize : summary / arsPageSize + 1;
					CountDownLatch latch = new CountDownLatch(num);
					for (int i = 1; i <= num; i++) {
						Future<Integer> submit = pool.submit(new AbilityRecThread(i, url, latch, lock));
						list.add(submit);
					}
					latch.await();
					boolean flag = list.stream().allMatch(s -> {
						try {
							return s.get() > 0;
						} catch (InterruptedException e) {
							e.printStackTrace();
						} catch (ExecutionException e) {
							e.printStackTrace();
						}
						return false;
					});
					if (flag) {
						msg = "数据处理成功!";
						fFlagResult.setIsSuccess(1);
					} else {
						msg = "数据处理失败!";
						fFlagResult.setIsSuccess(0);
					}
					pool.shutdown();

				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logBean.setfContext(ExceptionUtils.getMessage(e));
			fFlagResult.setIsSuccess(0);
			fFlagResult.setErrorMsg(JSONObject.toJSONString(msg) + "---系统异常--" + ExceptionUtils.getMessage(e));
		} finally {
			logBean.setfContext(msg);
			logBean.setfOutparmter(JSONObject.toJSONString(fFlagResult));
			logBean.setfInterfaceEndtime(new Date());
			spiFactory.execute("order.backend.saveLogBean", logBean);
			log.info("------------------对账明细查询能力自动执行完毕-----------------");
		}
		return fFlagResult;
	}

	// 获取接口入参
	public Map<String, Object> getParam(int pageNum, int pageSize) {
		Map<String, Object> packageParam = new HashMap<String, Object>();
		LocalDateTime plusDays = LocalDateTime.now().plusDays(-1);
		packageParam.put("search_time", plusDays.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
		packageParam.put("pageNum", pageNum);
		packageParam.put("pageSize", pageSize);
		return packageParam;
	}

	// 处理任务的线程
	class AbilityRecThread implements Callable<Integer> {
		private int pageNum;
		private String url;
		private CountDownLatch latch;
		private Lock lock;

		public AbilityRecThread(int pageNum, String url, CountDownLatch latch, Lock lock) {
			this.pageNum = pageNum;
			this.url = url;
			this.latch = latch;
			this.lock = lock;
		}

		@Override
		public Integer call() throws Exception {
			Map<String, Object> param = getParam(pageNum, arsPageSize);
			Map<String, String> headers = new HashMap<String, String>();
			headers.put("Content-Type", "application/json");
			lock.lock();
			ResponseInfo httpResult = null;
			try {
				httpResult = HttpClientUtils.HttpPostClient(url, JSONObject.toJSONString(param), headers, null, null,
						null, true);
			} finally {
				lock.unlock();
			}
			int num = 0;
			if (null != httpResult && 200 == httpResult.getHttpStatusCode()) {
				int code = (int) JSONPath.read(httpResult.getResponseBody(), "$.code");
				if (code == 0) {
					String data = JSONPath.read(httpResult.getResponseBody().toString(), "$.data").toString();
					num = HessianInfUtil.getData("reconciliationDetailsServiceImpl", "saveReconciliatioDetails", data);
				}
			}
			latch.countDown();
			return num;
		}
	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值