任何遊戲都至少需要運作兩個線程,主線程和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) {
return null;
wait();
return (runnable)taskqueue.removefirst();
關閉線程池,所有線程停止,不再執行任務
public synchronized void close() {
if (isalive) {
isalive = false;
taskqueue.clear();
interrupt();
關閉線程池并等待所有線程完成,執行等待的任務
public void join() {
//告訴等待線程線程池已關
synchronized (this) {
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;
task = gettask();
// 若gettask()傳回null或中斷,則關閉此線程并傳回
if (task == null) {
return;
// 運作任務,吸收異常
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");
" numtasks - integer: number of task to run.");
" numthreads - integer: number of threads " +
"in the thread pool.");
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() {
system.out.println("task " + taskid + ": start");
// 增加耗時
thread.sleep(500);
system.out.println("task " + taskid + ": end");
};
******************************************************
這樣的線程池可以在許多地方應用!