您的位置:首页 > 其它

ThreadLocal使用

2015-05-30 16:43 381 查看
首先直接看如何使用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的处理类上进行操作。

感觉思想真的很简单,但是有一个问题,如果处理的过程很多,同一个处理线程里,多个线程(不可能的啦),是不是会奔溃掉。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: