ThreadLocal使用

首先直接看如何使用ThreadLocal


public class TaobaoPurchaseTaskNettyHandler {
	private static final String END_WORKING_TIME = "230000";
	private static Logger logger = LoggerFactory.getLogger(TaobaoPurchaseTaskNettyHandler.class);
	private static ThreadLocal<TaobaoPurchaseOperatorNetty> operatorThreadLocal = new ThreadLocal<>();
	public static CheckPricePlaceOrderAndPayResponse placeOrderAndPay(CheckPricePlaceOrderAndPayRequest placeOrderAndPayRequest)throws Exception{
//	if(!checkPriceOrder.getOldOrderId().equals("75579381339"))
//			return;
//		if(!task.getTaobaoOrderId().equals("75167292951"))
//			return;
		MDC.put(CrawlerConstants.MDC_TRACEID_PLACEHOLDER, RandomStringUtils.randomAlphanumeric(10));
		//TaobaoPurchaseOperation.isOrderNeedTaobaoPurchase(task)&&
		if ( DateTimeUtil.time6().compareTo(END_WORKING_TIME) <= 0){
			logger.info(new Gson().toJson(placeOrderAndPayRequest));
			TaobaoPurchaseOperatorNetty operator = getOperator();
			return operator.OperateTaobaoPurchase(placeOrderAndPayRequest);
		}else{
			
		return null;
		}
	}

	private static TaobaoPurchaseOperatorNetty getOperator(){
		TaobaoPurchaseOperatorNetty operator = operatorThreadLocal.get();
		if(operator == null){
			operator = new TaobaoPurchaseOperatorNetty();
			operatorThreadLocal.set(operator);
		}
		return operator;
	}
}

主要三个步骤,1,你要处理那个类

2,是否在一个ThreadLocal里,没有的话,就新建一个,如果有的话,就从ThreadLocal里取出来

3,最后在ThreadLocal的处理类上进行操作。

感觉思想真的很简单,但是有一个问题,如果处理的过程很多,同一个处理线程里,多个线程(不可能的啦),是不是会奔溃掉。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值