您的位置:首页 > 编程语言 > Java开发

java游戏编程(1-2)线程池

2005-07-12 20:20 429 查看
线程池顾名思义,它是执行所有任务的一组线程,也许你要限制同时网络连接或I/o连接所用的线程数,或要对处理器工作量很大的任务控制最大线程数。例子:
清单1.1ThreadPool。java
import java.util.LinkedList;
/**
A thread pool is a group of a limited number of threads that
are used to execute tasks.(线程池是一组线程,限制执行任务的线程数)
*/
public class ThreadPool extends ThreadGroup {
private boolean isAlive;
private LinkedList taskQueue;
private int threadID;
private static int threadPoolID;
/**
Creates a new ThreadPool.(创建新的线程)
@param numThreads The number of threads in the pool.
*/
public ThreadPool(int numThreads) {
super("ThreadPool-" + (threadPoolID++));
setDaemon(true);
isAlive = true;
taskQueue = new LinkedList();
for (int i=0; i<numThreads; i++) {
new PooledThread().start();
}
}

/**
Requests a new task to run. This method returns
immediately, and the task executes on the next available
idle thread in this ThreadPool.(请求新的任务。这个方法立即返回,任务在池中下一闲机线程中执行)
<p>Tasks start execution in the order they are received.
@param task The task to run. If null, no action is taken.
@throws IllegalStateException if this ThreadPool is
already closed.
*/
public synchronized void runTask(Runnable task) {
if (!isAlive) {
throw new 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();
}

/**
Closes this ThreadPool and returns immediately. All
threads are stopped, and any waiting tasks are not
executed. Once a ThreadPool is closed, no more tasks can
be run on this ThreadPool.(关闭这个线程池并立即返回。所有线程停止,不执行任何等待的任务。关闭一个线程池之后,这个线程池不能再运行任何任务)
*/
public synchronized void close() {
if (isAlive) {
isAlive = false;
taskQueue.clear();
interrupt();
}
}

/**
Closes this ThreadPool and waits for all running threads
to finish. Any waiting tasks are executed.
*/
public void join() {
// notify all waiting threads that this ThreadPool is no
// longer alive
synchronized (this) {
isAlive = false;
notifyAll();
}
// wait for all threads to finish(这个线程并等待所有运行线程完成,执行任何等待的任务)
Thread[] threads = new Thread[activeCount()];
int count = enumerate(threads);
for (int i=0; i<count; i++) {
try {
threads[i].join();
}
catch (InterruptedException ex) { }
}
}

/**
A PooledThread is a Thread in a ThreadPool group, designed
to run tasks (Runnables).
*/
private class PooledThread extends Thread {

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

public void run() {
while (!isInterrupted()) {
// get a task to run
Runnable task = null;
try {
task = getTask();
}
catch (InterruptedException ex) { }
// if getTask() returned null or was interrupted,
// close this thread by returning.
if (task == null) {
return;
}
// run the task, and eat any exceptions it throws
try {
task.run();
}
catch (Throwable t) {
uncaughtException(this, t);
}
}
}
}
}
现在介绍ThreadGroup.ThreadGroup包括一组线程和一些修改线程的方法,如下代码中,使用ThreadGroup类的interrupt()方法用于在关闭线程池是停止等待所有等待的线程。下面用清单1.2 所示的ThreadPoolTest类测试ThreadPool对象。测试中,ThreadPoolTest会在线程池中启动几个线程,并指定几个任务让线程池去运行。因为程序要取得任务和线程数的变元,所以在测试时,要在命令行中输入如下代码:java ThreadPoolTest 8,4
清单1.2ThreadPoolTest.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]);
// create the thread pool
ThreadPool threadPool = new ThreadPool(numThreads);
// run example tasks
for (int i=0; i<numTasks; i++) {
threadPool.runTask(createTask(i));
}
// close the pool and wait for all tasks to finish.
threadPool.join();
}

/**
Creates a simple Runnable that prints an ID, waits 500
milliseconds, then prints the ID again.
*/
private static Runnable createTask(final int taskID) {
return new Runnable() {
public void run() {
System.out.println("Task " + taskID + ": start");
// simulate a long-running task
try {
Thread.sleep(500);
}
catch (InterruptedException ex) { }
System.out.println("Task " + taskID + ": end");
}
};
}
}
由于向控制台打印消息几乎不需要时间,所以ThreadPoolTest类通过休眠500毫秒来模拟时间任务。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: