Java遊戲起步:(一)線程與線程池

來源:互聯網
上載者:User
任何遊戲都至少需要運行兩個線程,主線程和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");
}
};
}

}
******************************************************
這樣的線程池可以在許多地方應用!




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.