JAVA games started: (1) threads and thread pools

Source: Internet
Author: User

Any game must run at least two threads, the main thread and GUI thread.
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. Collections list;

/**
The thread pool is a group of threads that limit the number of threads that execute tasks.
*/
Public class threadpool extends threadgroup {

Private Boolean isalive;
Private queue list taskqueue;
Private int threadid;
Private Static int threadpoolid;

/**
Create 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 queue list ();
For (INT I = 0; I <numthreads; I ++ ){
New pooledthread (). Start ();
}
}
/**
Request a new task. Characters are running in the next idle thread in the pool, and tasks are executed in the order they are received.
*/
Public synchronized void runtask (runnable task ){
If (! Isalive ){
Throw new illegalstateexception (); // If the thread is off, an illegalstateexception exception is thrown.
}
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 ();
}

/**
Close the thread pool. All threads stop and no longer execute tasks.
*/
Public synchronized void close (){
If (isalive ){
Isalive = false;
Taskqueue. Clear ();
Interrupt ();
}
}

/**
Close the thread pool and wait for all threads to complete the waiting task.
*/
Public void join (){
// Tell the waiting thread that the thread pool is off
Synchronized (this ){
Isalive = false;
Policyall ();
}

// Wait for all threads to finish
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 ()){

// Obtain the task
Runnable task = NULL;
Try {
Task = gettask ();
}
Catch (interruptedexception ex ){}

// If gettask () returns NULL or interrupted, the thread is closed and the system returns
If (task = NULL ){
Return;
}

// Run the task and absorb exceptions
Try {
Task. Run ();
}
Catch (throwable t ){
Uncaughtexception (this, t );
}
}
}
}
}
**************************************** *****
To test this thread pool, you can use the following test program!
**************************************** *****
(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 tasks 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 = new threadpool (numthreads );

// Run the task
For (INT I = 0; I <numtasks; I ++ ){
Threadpool. runtask (createtask (I ));
}

// Close the thread pool and wait until all tasks are completed
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 the time consumption
Try {
Thread. Sleep (500 );
}
Catch (interruptedexception ex ){}

System. Out. println ("task" + taskid + ": End ");
}
};
}

}
**************************************** **************
This 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.