任何游戲都至少需要運行兩個線程,主線程和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();
}
/**
關閉線程池,所有線程停止,不再執行任務
新聞熱點
疑難解答