任何遊戲都至少需要運行兩個線程,主線程和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");
}
};
}
}
******************************************************
這樣的線程池可以在許多地方應用!