ITeye博客

线程池的实现例子2

tobemoved · 2008-07-08 10:25 · java代码 · Markdown

** 线程池是一组线程,限制执行任务的线程数 */ public class ThreadPool extends ThreadGroup {

private boolean isAlive;
private LinkedList taskQueue;
private int threadID;
private static int threadPoolID;

/**
    创建新的线程池,numThreads是池中的线程数
*/
public ThreadPool(int numThreads) {
    super("ThreadPool-" + (threadPoolID++));
    setDaemon(true);

    isAlive = true;

    taskQueue = new LinkedList();
    for (int i=0; i<numThreads; i++) {
        new PooledThread().start();
    }
}
/**
    请求新任务。人物在池中下一空闲线程中运行,任务按收到的顺序执行
*/
public synchronized void runTask(Runnable task) {
    if (!isAlive) {
        throw new IllegalStateException();//线程被关则抛出IllegalStateException异常
    }
    if (task != null) {
        taskQueue.add(task);
        notify();
    }

}


protected synchronized Runnable getTask()
    throws InterruptedException
{
    while (taskQueue.size() == 0) {
        if (!isAlive) {
            return null;
        }
        wait();
    }
    return (Runnable)taskQueue.removeFirst();
}


/**
    关闭线程池,所有线程停止,不再执行任务
*/
public synchronized void close() {
    if (isAlive) {
        isAlive = false;
        taskQueue.clear();
        interrupt();
    }
}


/**
    关闭线程池并等待所有线程完成,执行等待的任务
*/
public void join() {
    //告诉等待线程线程池已关
    synchronized (this) {
        isAlive = false;
        notifyAll();
    }

    // 等待所有线程完成
    Thread threads = new Thread;
    int count = enumerate(threads);
    for (int i=0; i<count; i++) {
        try {
            threads*.join();
        }
        catch (InterruptedException ex) { }
    }
}


/**
    用于进行任务的线程
*/
private class PooledThread extends Thread {


    public PooledThread() {
        super(ThreadPool.this,
            "PooledThread-" + (threadID++));
    }


    public void run() {
        while (!isInterrupted()) {

            // 得到任务
            Runnable task = null;
            try {
                task = getTask();
            }
            catch (InterruptedException ex) { }

            // 若getTask()返回null或中断,则关闭此线程并返回
            if (task == null) {
                return;
            }

            // 运行任务,吸收异常
            try {
                task.run();
            }
            catch (Throwable t) {
                uncaughtException(this, t);
            }
        }
    }
}

}


要测试这个线程池,可以通过下面这个Test程序!


(ThreadPoolTest.java) public class ThreadPoolTest {

public static void main(String args) {
    if (args.length != 2) {
        System.out.println("Tests the ThreadPool task.");
        System.out.println(
            "Usage: java ThreadPoolTest numTasks numThreads");
        System.out.println(
            "  numTasks - integer: number of task to run.");
        System.out.println(
            "  numThreads - integer: number of threads " +
            "in the thread pool.");
        return;
    }
    int numTasks = Integer.parseInt(args);
    int numThreads = Integer.parseInt(args);

    // 生成线程池
    ThreadPool threadPool = new ThreadPool(numThreads);

    // 运行任务
    for (int i=0; i<numTasks; i++) {
        threadPool.runTask(createTask(i));
    }

    // 关闭线程池并等待所有任务完成
    threadPool.join();
}


/**
    一个简单的任务(打印ID)
*/
private static Runnable createTask(final int taskID) {
    return new Runnable() {
        public void run() {
            System.out.println("Task " + taskID + ": start");

            // 增加耗时
            try {
                Thread.sleep(500);
            }
            catch (InterruptedException ex) { }

            System.out.println("Task " + taskID + ": end");
        }
    };
}

}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。