java线程池demo

阅读更多
接口
/**
 * Project Name:chenxun-framework-start
 * File Name:ThreadPool.java
 * Package Name:com.chenxun.framework.test
 * Date:2016年9月2日下午1:51:44
 * Copyright (c) 2016, www midaigroup com Technology Co., Ltd. All Rights Reserved.
 *
*/

package com.chenxun.framework.test;
/**
 * ClassName:ThreadPool 
* Function: TODO ADD FUNCTION.
* Reason: TODO ADD REASON.
* Date: 2016年9月2日 下午1:51:44
* @author 陈勋 * @version * @since JDK 1.7 * @see */ public interface ThreadPool { /** * * execute:(执行job).
* @author 陈勋 * @param job * @since JDK 1.7 */ void execute(Job job); /** * * shutdown:(关闭线程池).
* * @author 陈勋 * @since JDK 1.7 */ void shutdown(); /** * * addWorkers:(增加工作者线程).
* @author 陈勋 * @param num * @since JDK 1.7 */ void addWorkers(int num); /** * * removeWorker:(减少工作者线程).
* @author 陈勋 * @param num * @since JDK 1.7 */ void removeWorker(int num); /** * * getJobSize:(获取等待执行的任务数量).
* * @author 陈勋 * @return * @since JDK 1.7 */ int getJobSize(); }

接口实现
/**
 * Project Name:chenxun-framework-start
 * File Name:DefualtThreadPool.java
 * Package Name:com.chenxun.framework.test
 * Date:2016年9月2日下午1:55:35
 * Copyright (c) 2016, www midaigroup com Technology Co., Ltd. All Rights Reserved.
 *
*/

package com.chenxun.framework.test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

/**
 * ClassName:DefualtThreadPool 
* Function: TODO ADD FUNCTION.
* Reason: TODO ADD REASON.
* Date: 2016年9月2日 下午1:55:35
* @author 陈勋 * @version * @since JDK 1.7 * @see */ public class DefualtThreadPool implements ThreadPool { //线程池最大限制数 private static final int MAX_WORKER_NUMBERS=10; //线程池默认数量 private static final int DEFAULT_WORKER_NUMBERS=5; //线程池最小连接数量 private static final int MIN_WORKER_NUMBERS=1; //工作列表 private final LinkedList jobs=new LinkedList(); //工作者列表 private final List workers=Collections.synchronizedList(new ArrayList()); private int workerNum=MIN_WORKER_NUMBERS; //线程编号生成 private AtomicLong threadNum=new AtomicLong(); public DefualtThreadPool(){ initializeWorkers(DEFAULT_WORKER_NUMBERS); } public DefualtThreadPool(int num){ workerNum= num>MAX_WORKER_NUMBERS&&numMAX_WORKER_NUMBERS){ num=MAX_WORKER_NUMBERS-this.workerNum; } initializeWorkers(num); this.workerNum+=num; } } @Override public void removeWorker(int num) { synchronized (jobs) { if(num>=this.workerNum){ throw new IllegalArgumentException("beyond workNum"); } int count=0; while(count

你可能感兴趣的:(java,thread)