Java游戏起步:(一)线程与线程池

类别:Java 点击:0 评论:0 推荐:

任何游戏都至少需要运行两个线程,主线程和GUI线程
而线程池是一个管理运行线程的有用工具,下面的代码示范了一个线程池的实现方法~~
************************************************
(ThreadPool.java)
import java.util.LinkedList;

/**
    线程池是一组线程,限制执行任务的线程数
*/
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[activeCount()];
        int count = enumerate(threads);
        for (int i=0; i<count; i++) {
            try {
                threads[i].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[0]);
        int numThreads = Integer.parseInt(args[1]);

        // 生成线程池
        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");
            }
        };
    }

}
******************************************************
这样的线程池可以在许多地方应用!

本文地址:http://com.8s8s.com/it/it13607.htm