Java game programming (1-2) thread pool

Source: Internet
Author: User

As the name suggests, a thread pool is a group of threads that execute all tasks. You may need to limit the number of threads used for simultaneous network connections or I/O connections, or you need to control the maximum number of threads for a task with a large processor workload. Example:

Listing 1.1 threadpool. Java

Import java. util. Collections list;

/**
A thread pool is a group of a limited number of threads that
Are used to execute tasks. (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;

/**
Creates a new threadpool. (create a thread)
@ Param numthreads 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 ();
}
}

/**
Requests a new task to run. This method returns
Immediately, and the task executes on the next available
Idle thread in this threadpool. (request a new task. This method returns immediately, and the task is executed in the next idle thread in the pool)
<P> tasks start execution in the order they are already ed.
@ Param task the task to run. If null, no action is taken.
@ Throws illegalstateexception if this threadpool is
Already closed.
*/
Public synchronized void runtask (runnable task ){
If (! Isalive ){
Throw new illegalstateexception ();
}
If (task! = NULL ){
Taskqueue. Add (task );
Notify ();
}

}

protected synchronized runnable gettask ()
throws interruptedexception
{< br> while (taskqueue. Size () = 0) {
If (! Isalive) {
return NULL;
}< br> wait ();
}< br> return (runnable) taskqueue. removefirst ();
}

/**
closes this threadpool and returns immediately. all
threads are stopped, and any waiting tasks are not
executed. once a threadpool is closed, no more tasks can
be run on this threadpool. (close this thread pool and return immediately. All threads stop and do not execute any waiting tasks. After a thread pool is closed, no tasks can be run in this thread pool.)
*/
Public synchronized void close () {
If (isalive) {
isalive = false;
taskqueue. clear ();
interrupt ();
}< BR >}

/**
closes this threadpool and waits for all running threads
to finish. any waiting tasks are executed.
*/
Public void join () {
// every y all waiting threads that this threadpool is no
// longer alive
synchronized (this) {
isalive = false;
policyall ();
}

// wait for all threads to finish (this thread is waiting for all running threads to finish and execute any waiting tasks)
thread [] threads = new thread [activecount ()];
int COUNT = enumerate (threads);
for (INT I = 0; I try {
threads [I]. join ();
}< br> catch (interruptedexception ex) {}< BR >}

/**
A pooledthread is a thread in a threadpool group, designed
To run tasks (runnables ).
*/
Private class pooledthread extends thread {

Public pooledthread (){
Super (threadpool. This,
"Pooledthread-" + (threadid ++ ));
}

Public void run (){
While (! Isinterrupted ()){

// get a task to run
runnable task = NULL;
try {
task = gettask ();
}< br> catch (interruptedexception ex) {}

// If gettask () returned null or was interrupted,
// close this thread by returning.
If (task = NULL) {
return;
}

// run the task, and eat any exceptions it throws
try {
task. run ();
}< br> catch (throwable t) {
uncaughtexception (this, t );
}< BR >}

Threadgroup. threadgroup includes a set of threads and methods for modifying threads.CodeThe interrupt () method of the threadgroup class is used to stop all waiting threads in the thread pool. The following uses the threadpooltest class shown in listing 1.2 to test the threadpool object. In the test, threadpooltest starts several threads in the thread pool and specifies several tasks for the thread pool to run. BecauseProgramTo get the variable of the number of tasks and threads, enter the following code in the command line during the test: Java threadpooltest 8, 4

List 1.2threadpooltest.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]);

// Create the thread pool
Threadpool = new threadpool (numthreads );

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

// Close the pool and wait for all tasks to finish.
Threadpool. Join ();
}

/**
Creates a simple runnable that prints an ID, Waits 500
Milliseconds, then prints the ID again.
*/
Private Static runnable createtask (final int taskid ){
Return new runnable (){
Public void run (){
System. Out. println ("task" + taskid + ": Start ");

// Simulate a long-running task
Try {
Thread. Sleep (500 );
}
Catch (interruptedexception ex ){}

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

}
Since it takes almost no time to print messages to the console, the threadpooltest class simulates time tasks by sleeping for 500 milliseconds.

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.