在工作中,有些时候需要用到线程来提高程序的性能。
如:在某个操作需要完成的事情,但不直接反映操作结果的内容,可以通过异步线程完成。
大量数据的导出,推送等,可以使用线程池。
下面写点实例代码:
1.单个线程处理
//接口工具类,隐藏了一些东西,总体流程是:在业务代码处调用工具类,传入对应参数,对参数进行判断并执行对应方法
package com.client.util;
import java.io.IOException;import java.util.HashMap;import java.util.Map;import java.util.PRoperties;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import net.sf.json.JSONObject;import org.apache.commons.collections.MapUtils;import org.apache.commons.lang.StringUtils;import org.apache.log4j.Logger;import redis.clients.jedis.Jedis;public class CancelOrderThreadUtil {public Logger logger = Logger.getLogger(CancelOrderThreadUtil.class.getName());private String escOrderId;private String usrOnlyId;private String Listid;private Long count;private String deleveryOrderId;private String type;private Long itemid;private Long zoneId;public CancelOrderThreadUtil(String escOrderId,String usrOnlyId,String Listid,Long count,String deleveryOrderId,String type,Long itemid,Long zoneId){this.escOrderId = escOrderId;this.usrOnlyId = usrOnlyId;this.Listid = Listid;this.count = count;this.deleveryOrderId = deleveryOrderId;this.type = type;this.itemid = itemid;this.zoneId = zoneId;}public void execute(){ExecutorService si = Executors.newSingleThreadExecutor();si.execute(new Runnable() { public void run() { try{ if(FxDeleveryConstant.CANCEL_ORDER_THREAD_TYPE.equals(type)){ Properties properties = PropertyUtil.get("dependProjectConfig.properties"); String cancelOrderUrl = properties.getProperty("CANCEL_ORDER_URL"); logger.info("cancelOrderUrl :" + cancelOrderUrl); Map<String,Object> params = new HashMap<String, Object>(); params.put("orderNumber", deleveryOrderId); JSONObject js = null; try { js = HttpInterfaceCallUtil.httpInterfaceCall(params, cancelOrderUrl); } catch (IOException e) { logger.info("失败!"); } if(null == js){ logger.info("失败!"); }else{ logger.info("cancel http code :"+MapUtils.getString(js, "code")); if(!FxDeleveryConstant.ALL_SUCCESSFUL.equals(MapUtils.getString(js, "code"))){ logger.info("失败!"); } } }else if(FxDeleveryConstant.CANCEL_ORDER_THREAD_TYPE_RETURNED.equals(type)){ RefundLimitUtil.refundLimit(usrOnlyId, itemid, count.toString(), escOrderId, zoneId); }else{ ItemServiceClient itemServiceClient = ItemTools.getItemServiceClient(); itemServiceClient.sellItem(itemid, -count.intValue()); } }catch (Exception e) { logger.error(e,e); } } }); si.shutdown();}}
页面调用:
CancelOrderThreadUtil cth = new CancelOrderThreadUtil(ctocOrder.getEscOrderid(), rdOrder.getBuyerUsronlyid().toString(), r.getListId().toString(), r.getDeliveryCount(), null, FxDeleveryConstant.CANCEL_ORDER_THREAD_TYPE_RETURNED,r.getItemId(),Long.parseLong(ctocOrder.getSellerNote6()));cth.execute();
2.线程池
ExecutorService ex = Executors.newFixedThreadPool(1);
ex.execute(new Runnable() {public void run() {try {long startTime2 = System.currentTimeMillis();List<ExportDto> exportOrders = new ArrayList<ExportDto>();ExecutorService ex = Executors.newFixedThreadPool(totalPage);for (int i = 1; i <= totalPage; i++) {final int j = i;Future<List<ExportDto>> result = ex.submit(new Callable<List<ExportDto>>() {public List<ExportOrderDetailDto> call(){List<ExportOrderDetailDto> tempAll = new ArrayList<ExportOrderDetailDto>();try {queryOrder.setPageIndex(j);ReturnOrderDto tempOrder = client.queryFxOrder(queryOrder);for (FxOrderNewDto fond : tempOrder.getOrders()) {long startTime3 = System.currentTimeMillis();List<ExportOrderDetailDto> tempList = client.exportOrderDrtail(fond.getEscOrderId());tempAll.addAll(tempList);long endTime3 = System.currentTimeMillis();logger.info("处理订单:"+fond.getEscOrderId()+"--耗时:"+(endTime3 - startTime3) + "ms");}} catch (Exception e) {logger.error(e);}return tempAll;}});exportOrders.addAll(result.get());}Client.updateOpcDownloadByData( exportOrders);} catch (Exception e) {logger.error(e.getMessage(),e);}}});ex.shutdown();新闻热点
疑难解答