java线程池--自己编写的线程池,非Eclipse自带

package threadPool;


import java.util.Vector;


// TODO: Auto-generated Javadoc
/**
 * 线程池应该是这样一个概念: 维护一个线程队列,该队列始终运行 维护一个工作队列, 当发现有空余线程,则将任务交给该线程.
 */
public class ThreadPool {


/** 线程池的最大容量,也就是能容纳多少的线程. */
protected int maxPoolSize;


/** 线程池初始化大小. */
protected int initPoolSize;


/** 线程池中的线程队列,该队列始终运行. */
protected Vector<PooledThread> threads = new Vector<PooledThread>();


/** 线程池初始化标志. */
protected boolean initialized = false;


/** 线程池中是否含有空闲线程的标志. */
protected boolean hasIdleThread = false;


/** 线程池中的任务队列. */
protected Vector<ThreadTask> taskQueue = new Vector<ThreadTask>();


/** The url vector. */
// protected Vector<UrlStruct> urlVector = new Vector<UrlStruct>();


/** 已添加的任务所属的类名的队列. */
protected Vector<String> nameList = new Vector<String>();


/** 停止分配线程的标志. */
private boolean stopAssignedThread = false;


/** 任务队列中最大的任务数. */
private final int MAX_TASK_QUEUE = 10;


/**
* 构造函数.

* @param maxPoolSize
*            线程池最大可容纳线程的数量
* @param initPoolSize
*            初始化时线程池中线程数
*/
public ThreadPool(int maxPoolSize, int initPoolSize) {
this.maxPoolSize = maxPoolSize;
this.initPoolSize = initPoolSize;
init();// 初始化线程池
// 运行线程池的线程,主要是用来分配任务,维护任务队列和线程队列
Thread assignThread = new Thread(new Runnable() {


@Override
public void run() {
assignTask();
}
});
assignThread.start();
}


/**
* 线程池初始化函数,根据初始线程池容量,生成对应数目的线程。.
*/
private void init() {
initialized = true;
for (int i = 0; i < initPoolSize; i++) {
PooledThread thread = new PooledThread("第" + String.valueOf(i)
+ "线程");
thread.start();
threads.add(thread);
}
}


/**
* 设置线程池的最大容量.

* @param maxPoolSize
*            线程池的最大容量
*/
public void setMaxPoolSize(int maxPoolSize) {
this.maxPoolSize = maxPoolSize;
reSetPoolSize(maxPoolSize);
}


/**
* 重设当前线程数 若需杀掉某线程,线程不会立刻杀掉,而会等到线程中的事务处理完成 但此方法会立刻从线程池中移除该线程,不会等待事务处理结束.

* @param size
*            重新设置的线程池大小
*/
public void reSetPoolSize(int size) {
if (!initialized) {
initPoolSize = size;
return;
} else if (size > getPoolSize())// size大于当前线程池容量,则新增size-getPoolSize()个数的线程
{
for (int i = getPoolSize(); i < size && i < maxPoolSize; i++) {
PooledThread thread = new PooledThread("第" + String.valueOf(i)
+ "线程");
thread.start();
threads.add(thread);
}
} else if (size < getPoolSize())// size小于当前线程池容量,则杀死getPoolSize()-size个数的线程
{
while (getPoolSize() > size) {
PooledThread th = (PooledThread) threads.remove(0);
th.kill();
}
}
}


/**
* 获取当前线程池中线程的个数.

* @return 当前线程池中的线程个数
*/
public int getPoolSize() {
return threads.size();
}


/**
* 设置休眠.

* @param sleepTime
*            the new to sleep
*/
protected void setToSleep(int sleepTime) {
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}


}


/**
* 空闲线程应该是: 当前没有在运行的线程.

* @return 返回一个空闲的线程
*/
public synchronized PooledThread getIdleThread() {
for (int i = 0; i < threads.size(); i++) {
PooledThread thread = threads.get(i);
if (!thread.isRunning()) {
return thread;
}
}
return null;
}


/**
* 增加一个Task到线程池,由线程池分配.

* @param task
*            新增的任务
* @return 返回增加的结果,成功返回true,否则返回false
*/
public boolean addTaskToPool(ThreadTask task) {
// System.out.println("线程中的任务队列长度:"+taskQueue.size());
if (taskQueue.size() < MAX_TASK_QUEUE) {
String name = task.getClass().getName();
if (name.endsWith("GetUrlStruct") || name.endsWith("WritetoDB")
|| name.endsWith("probabilityTask")) {
int i = 0;
synchronized (taskQueue) {
while (i < taskQueue.size()) {
if (name.equals(taskQueue.get(i).getClass().getName()))
return false;
i++;
}
}
}
taskQueue.add(task);
return true;
}
return false;
}


/**
* 工作分配.
*/
private void assignTask() {
while (!stopAssignedThread) {
if (taskQueue.size() == 0) {
setToSleep(400);
continue;
}
PooledThread th = getIdleThread();
if (th != null) {
ThreadTask task = getLastTask();
if (task != null) {
task.setWorkThreadName(th.getName());
th.putTask(task);
th.startTask();
}
}
}
}


/**
* 从任务队列中获取一个任务.

* @return 返回一个任务ThreadTask结构
*/
private synchronized ThreadTask getLastTask() {
int size = taskQueue.size();
if (size > 0) {
return taskQueue.remove(size - 1);
}
return null;
}


/**
* 清除池中所有线程.
*/
public void clearPool() {
int size = threads.size();
stopAssignedThread = true;
for (int i = 0; i < size; i++) {
PooledThread t = threads.get(i);
t.kill();
}


while (!isAllThreadDead()) {
setToSleep(200);
}
}
/**
* Checks if is all thread dead.

* @return true, if is all thread dead
*/
public boolean isAllThreadDead() {
int size = threads.size();
for (int i = 0; i < size; i++) {
PooledThread t = threads.get(i);
if (t.isAlive()) {
return false;
}
}
return true;
}


/**
* 判断当前空闲线程的数量.

* @return 返回当前空闲线程的数量
*/
public synchronized int getIdleThreadNum() {
int num = 0;
for (int i = 0; i < threads.size(); i++) {
if (threads.get(i).running == false)
num++;
}
return num;
}

/**
* Gets the task queue size.

* @return the task queue size
*/
public synchronized int getTaskQueueSize() {
return taskQueue.size();
}

}




package threadPool;

/**
 * The Class PooledThread.
 */
public class PooledThread extends Thread 
{
   
    /** The task. */
    protected ThreadTask task;
    //线程跑动的标志־
    /** The running. */
    protected boolean running = false;
    //线程处理的所有工作是否要终止
    /** The stopped. */
    protected boolean stopped = false;
    //线程处理的所有工作是否暂停
    /** The paused. */
    protected boolean paused = false;
    //是否要杀死当前线程
    /** The killed. */
    protected boolean killed = false;
    
    //最大任务数目,如果任务数小于MAX_TASK_SIZE,则表明线程是空闲的
   
    /**
     * Instantiates a new pooled thread.
     *
     * @param threadId the thread id
     */
    public PooledThread(String threadId){
        super(threadId);
    }
   
    /**
     * Put task.
     *
     * @param task the task
     */
    public synchronized void putTask(ThreadTask task)
    {
        this.task = task;
    }
   
   
    /**
     * Checks if is running.
     *
     * @return true, if is running
     */
    public synchronized boolean isRunning()
    {
        return running;
    }
   
    /**
     * Stop tasks.
     */
    public synchronized void stopTasks()
    {
        stopped = true;
    }
    


/**
* Clear task.
*/
private synchronized void clearTask() 
{
task = null;
}
   
   
    /**
     * Pause task.
     */
    public synchronized void pauseTask()
    {
        paused = true;
    }
    
    /**
     * Continue task.
     */
    public synchronized void continueTask()
    {
        paused = false;
    }
   
    /**
     * Kill.
     */
    public synchronized void kill()
    {
    killed = true;
    }
   
   
    /**
     * Start task.
     */
    public synchronized void startTask()
    {
        running = true;
    }
   
    /* (non-Javadoc)
     * @see java.lang.Thread#run()
     */
    public void run() 
    {
    while(true)
    {
    if (running) 
{
    //synchronized(Storage.class)
    {
    processTask();
   running = false;
}
}
    else
    {
    setToSleep(200);
    }
    if (killed) 
{
return;
}
    }

}
    
    /**
     * 设置休眠.
     *
     * @param sleepTime the new to sleep
     */
    protected void setToSleep(int sleepTime) 
    {
try 
{
Thread.sleep(sleepTime);

catch (InterruptedException e) 
{
e.printStackTrace();
}


}


/**
* Process task.
*/
private synchronized void processTask() 
{
if (stopped) {
clearTask();
return;
}
if (paused) 
{
return;
}
if(task != null)
{
task.work();
clearTask();
}
}
    
}


package threadPool;


/**
 * 线程任务接口,任何实现该接口的类,只要实现自己的work函数即可,
 * work函数中可以添加自己的处理代码.
 *
 * @author ryang
 * 2006-8-8
 */
public interface ThreadTask {
    
    /**
     * Work.
     */
    public abstract void work();
    
    public abstract String setWorkThreadName(String name);
}




/**
* 测试方法

* @param args
*/
public static void main(String[] args) {
ThreadPool pool = new ThreadPool(2, 2);
for (int i = 0; i < 10; i++) {
GetWorkTasks task = new GetWorkTasks("线程名称:"+i+"");
while (pool.addTaskToPool(task) == false) {//注意这里要是while循环,这样如果加入失败可以循环继续加入
}
}
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值