Java Game start: (a) thread and thread pool

Source: Internet
Author: User
Tags count integer join return thread
Any game needs to run at least two threads, the main thread and GUI threads


While the thread pool is a useful tool for managing running threads, the following code demonstrates how to implement a thread pool ~ ~


************************************************


(Threadpool.java)


import java.util.LinkedList;





/**

The
thread pool is a set of threads that limit the number of threads that perform a task


*/


public class ThreadPool extends Threadgroup {





private Boolean isAlive;


private LinkedList Taskqueue;


private int ThreadID;


private static int threadpoolid;





/**


creates a new thread pool, Numthreads is 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 ();


}


}


/**


Request a new task. The characters run in the next idle thread in the pool, and the tasks are executed in the order in which they are received


*/


public synchronized void Runtask (Runnable task) {


if (!isalive) {


throw new IllegalStateException ();//thread is off throws IllegalStateException exception


}


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 the thread pool, all threads stop, and no longer perform tasks


*/


public synchronized void Close () {


if (isAlive) {


isAlive = false;


taskqueue.clear ();


interrupt ();


}


}








/**


closes the thread pool and waits for all threads to complete, executing the waiting task


*/


public void Join () {


//Tell waiting thread pool is off


synchronized (this) {


isAlive = false;


Notifyall ();


}





//Waiting for all threads to complete


thread[] Threads = new Thread[activecount ()];


int count = enumerate (threads);


for (int i=0; i<count; i++) {


try {


Threads[i].join ();


}


catch (Interruptedexception ex) {}


}


}








/**


the thread used for the task


*/


Private class Pooledthread extends Thread {








public Pooledthread () {


Super (Threadpool.this,


"pooledthread-" + (threadid++));


}








public void Run () {


while (!isinterrupted ()) {





//Get task


Runnable task = null;


try {


task = Gettask ();


}


catch (Interruptedexception ex) {}





//If Gettask () returns null or interrupts, this thread is closed and returned


if (task = null) {


return;


}





//Running task, absorbing abnormal


try {


Task.run ();


}


catch (Throwable t) {


uncaughtexception (this, t);


}


}


}


}


}


*********************************************


to test this thread pool, you can pass the test program below!


*********************************************


(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]);





//Generate thread pool


ThreadPool ThreadPool = new ThreadPool (numthreads);





//Run task


for (int i=0; i<numtasks; i++) {


Threadpool.runtask (CreateTask (i));


}





//Closes the thread pool and waits for all tasks to complete


Threadpool.join ();


}








/**


a simple task (print ID)


*/


private static Runnable createtask (final int taskID) {


return new Runnable () {


public void Run () {


System.out.println ("Task" + TaskID + ": Start");





//Increase time consuming


try {


Thread.Sleep (500);


}


catch (Interruptedexception ex) {}





System.out.println ("Task" + TaskID + ": End");


}


};


}





}


******************************************************


such a thread pool can be applied in many places!














Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.