Executor框架

1、Executor具体内容:点击打开链接

public class MyExcutor {
	public static void main(String[] args) {
		ThreadPoolExecutor executor = new ThreadPoolExecutor(
				1,	//	corePoolSize 创建时的线程数											
				2,	//maximumPoolSize ;corePoolSize不够时把任务放入队列BlockingQueue workQueue,若队列满了,则根据此数创建不超过次数的线程执行
				60, 	
				TimeUnit.SECONDS,
				new ArrayBlockingQueue<>(3) // BlockingQueue workQueue; corePoolSize不够时,任务放入的队列 分有界和无界
				,new MyRejected()  //拒绝策略 当前面3个都不满足的情况下的拒绝任务的策
				);
public class MyRejected implements RejectedExecutionHandler{

	@Override
	public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
		System.out.println("被拒绝的任务"+r.toString());
	}

}
		MyTask myTask1 = new MyTask(1,"任务1");
		MyTask myTask2 = new MyTask(2,"任务2");
		MyTask myTask3 = new MyTask(3,"任务3");
		MyTask myTask4 = new MyTask(4,"任务4");
		MyTask myTask5 = new MyTask(5,"任务5");
		MyTask myTask6 = new MyTask(6,"任务6");
		executor.execute(myTask1);
		executor.execute(myTask2);
		executor.execute(myTask3);
		executor.execute(myTask4);
		executor.execute(myTask5);
		executor.execute(myTask6);
		executor.shutdown();
		
	}

}

2、java自定义拒绝策略

http://blog.sina.com.cn/s/blog_714cb3040102wc6i.html

 

3、生产者消费者模式

http://ifeve.com/producers-and-consumers-mode/

 

 

4、Concurrent.util常用工具类

:http://blog.csdn.net/defonds/article/details/44021605/

6、某某商城的多线程

6.1、线程池

/**
 * 。。。。。
单例模式 * * @author ...... * */ public class ActMutexExecutorServiceUtil { /** * 等待子线程超时时间 */ private static final int AWAIT_TIME = 500; /** * 设置线程数量 */ public static final int THREAD_NUM = Runtime.getRuntime().availableProcessors(); private static Object obj = new Object(); private static ExecutorService executor = null; private ActMutexExecutorServiceUtil() { } /** * 获得一个固定线程池对象executor
线程池数量设定 {@link ActMutexExecutorServiceUtil#THREAD_NUM} * * @return ExecutorService */ public static ExecutorService getExecutorServiceInstance() { if (executor == null) { synchronized (obj) { if (executor == null) { executor = Executors.newFixedThreadPool(THREAD_NUM); } } } return executor; } /** * 重置线程池 */ public static void restartExecutor() { executor = null; getExecutorServiceInstance(); } /** * 关闭并等待子线程在指定时间内来完成处理
时间设定 {@link ActMutexExecutorServiceUtil#AWAIT_TIME}
超时强制关闭子线程
* * @throws BaseException 异常会强制立即关闭子线程 抛出异常 */ public static void shutDown() { executor.shutdown(); try { executor.awaitTermination(AWAIT_TIME, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { shutDownNowAndRestart(); throw new BaseException("SP-SERVICE-ExecutorServiceUtil.shutDown", e); } } /** * 立即关闭子线程并重置线程池 */ public static void shutDownNowAndRestart() { executor.shutdownNow(); restartExecutor(); } }

 

6.2、调用:前面省略一万行

// 。。。。。。。,启动多线程
            int currentInCmmdtyRangeListSize = currentInCmmdtyRangeList.size();
            if (currentInCmmdtyRangeListSize > cmmdtyRangeNumOfThread) {

                int groupCount = 0;
                if (currentInCmmdtyRangeListSize % cmmdtyRangeNumOfThread > 0) {
                    groupCount = currentInCmmdtyRangeListSize / cmmdtyRangeNumOfThread + 1;
                } else {
                    groupCount = currentInCmmdtyRangeListSize / cmmdtyRangeNumOfThread;
                }

                LOGGER.info(PromotionConstants.LOGGER_FORMAT, methodName, "分配任务个数 : " + groupCount + ",uuid:"
                        + checkInputDto.getUuid() + ",serialNo:" + checkInputDto.getSerialNo() + ",actCode:"
                        + checkInputDto.getActivityId());

                int fromIndex = 0;
                int toIndex = cmmdtyRangeNumOfThread;
                int tempToIndex = 0;

                // 获取线程池
                ExecutorService executor = ActMutexExecutorServiceUtil.getExecutorServiceInstance();

                Map>> cmmdtyRangeMap = new HashMap>>();

                List inCmmdtyRangeList = null;

                try {
                    for (int i = 0; i < groupCount; i++) {
                        inCmmdtyRangeList = ActMutexCheckUtil.getSplitCmmdtyRangeList(currentInCmmdtyRangeList,
                                fromIndex, toIndex);

                        cmmdtyRangeMap.put(i, executor.submit(new CommodityMutexCheckCallable(
                                commodityMutexCheckService, inCmmdtyRangeList, actGoodsSetDto
                                        .getCurExcludeCmmdtyCodeMap(), mutexActivityIdList, checkInputDto.getUuid(),
                                checkInputDto.getSerialNo(), checkInputDto.getActivityId())));

                        fromIndex = fromIndex + cmmdtyRangeNumOfThread;
                        tempToIndex = toIndex + cmmdtyRangeNumOfThread;
                        if (tempToIndex > currentInCmmdtyRangeListSize) {
                            toIndex = currentInCmmdtyRangeListSize;
                        } else {
                            toIndex = tempToIndex;
                        }
                    }
                } catch (RejectedExecutionException e) {
                    throw new BaseException(e);
                }

                try {
                    // 将多线程处理结果添加。。。。。
                    for (int i = 0; i < groupCount; i++) {
                        mutexCmmdtyRangeList.addAll(cmmdtyRangeMap.get(i).get());
                    }
                } catch (InterruptedException e) {
                    throw new BaseException(e);
                } catch (ExecutionException e) {
                    throw new BaseException(e);
                }

            } else {
                // 如果当前。。。。没超过指定件数,单线程进行。。
                mutexCmmdtyRangeList = commodityMutexCheckService.findMutexCmmdtyRangeList(currentInCmmdtyRangeList,
                        actGoodsSetDto.getCurExcludeCmmdtyCodeMap(), mutexActivityIdList, checkInputDto.getUuid(),
                        checkInputDto.getSerialNo(), checkInputDto.getActivityId());
            }

后面省略一万行

public class CommodityMutexCheckCallable implements Callable> {

    /**
     * 日志对象
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(CommodityMutexCheckCallable.class);

    private CommodityMutexCheckService commodityMutexCheckService;

    /**
     * 。。
     */
    private List currentInCmmdtyRangeList;

    /**
     * 。。
     */
    private Map> currentExCmmdtyRangeMap;

    /**
     * 。。
     */
    private List mutexActivityIdList;

    /**
     * uuid
     */
    private String uuid;

    /**
     * serialNo
     */
    private String serialNo;

    /**
     * 。。
     */
    private String activityId;

    public CommodityMutexCheckCallable(CommodityMutexCheckService commodityMutexCheckService,
            List currentInCmmdtyRangeList, Map> currentExCmmdtyRangeMap,
            List mutexActivityIdList, String uuid, String serialNo, String activityId) {
        super();
        this.commodityMutexCheckService = commodityMutexCheckService;
        this.currentInCmmdtyRangeList = currentInCmmdtyRangeList;
        this.currentExCmmdtyRangeMap = currentExCmmdtyRangeMap;
        this.mutexActivityIdList = mutexActivityIdList;
        this.uuid = uuid;
        this.serialNo = serialNo;
        this.activityId = activityId;
    }

    /*
     * (non-Javadoc)
     * @see java.util.concurrent.Callable#call()
     */
    @Override
    public List call() throws Exception {
        final String methodName = "call";
        LOGGER.info(PromotionConstants.TRACE_START, methodName);

        List list = commodityMutexCheckService.findMutexCmmdtyRangeList(currentInCmmdtyRangeList,
                currentExCmmdtyRangeMap, mutexActivityIdList, uuid, serialNo, activityId);//调用某某服务(将调用服务放入多线程中执行)

        LOGGER.info(PromotionConstants.TRACE_END, methodName);

        return list;
    }

}

 


 

Executor框架_第1张图片

 

Executor框架_第2张图片

 

 

你可能感兴趣的:(转载)