The role of the thread pool:
The thread pool is used to limit the number of execution threads in the system.
Depending on the system environment, you can automatically or manually set the number of threads to achieve the best running effect. This reduces the waste of system resources, resulting in low system congestion efficiency. Use the thread pool to control the number of threads and wait in queue for other threads. After a task is executed, the task starts from the top of the queue. If no process is waiting in the queue, this resource in the thread pool is waiting. When a new task needs to run, if there is a waiting working thread in the thread pool, it can start to run; otherwise, it enters the waiting queue.
Why thread pool:
- Reduces the number of times threads are created and destroyed. Each worker thread can be reused to execute multiple tasks.
- You can adjust the number of worker threads in the thread pool according to the system's capacity to prevent servers from getting tired due to excessive memory consumption (each thread requires about 1 MB of memory, the more threads open, the larger the memory consumed, and the machine crashes)
Thread Pool class
Package COM. TDT. impl. ls; import Java. util. using list;/*** @ project locationgateway * @ author sunnylocus * @ Verson 1.0.0 * @ date Aug 2, 2008 * @ JDK 1.4.2 */public class threadpool extends threadgroup {private Boolean isclosed = false; // whether the thread pool closes the private writable list workqueue; // The work queue Private Static int threadpoolid = 1; // idpublic threadpool (INT poolsize) {// poolsize indicates the number of worker threads in the thread pool. Super (threadpooli D + ""); // specify the threadgroup name setdaemon (true); // The inherited method to set whether to guard the thread pool workqueue = new queue list (); // create a work queue for (INT I = 0; I <poolsize; I ++) {New workthread (I ). start (); // create and start a working thread. If the number of thread pools is, add a new task to the working queue, the worker thread executes this task */Public synchronized void execute (runnable task) {If (isclosed) {Throw new illegalstateexception ();} If (task! = NULL) {workqueue. add (task); // Add a task y () to the queue; // wake up a gettask () the worker thread}/** of the task to be executed in the method retrieves a task from the work queue. The worker thread will call this method */private synchronized runnable gettask (INT threadid) throws interruptedexception {While (workqueue. size () = 0) {If (isclosed) return NULL; system. out. println ("working thread" + threadid + "waiting for task... "); wait (); // if there are no tasks in the work queue, wait for the task} system. out. println ("worker thread" + threadid + "start to execute the task... "); Return (runnable) workqueue. remove First (); // returns the first element in the queue and deletes it from the queue}/** closes the thread pool */Public synchronized void closepool () {If (! Isclosed) {waitfinish (); // wait for the worker thread to finish executing isclosed = true; workqueue. clear (); // clear the work queue interrupt (); // Interrupt all worker threads in the thread pool, this method inherits from the threadgroup class}/** wait for the worker thread to finish all tasks */Public void waitfinish () {synchronized (this) {isclosed = true; policyall (); // wake up all worker threads waiting for the task in the gettask () method} thread [] threads = new thread [activecount ()]; // activecount () returns the estimated value of the active thread in the thread group. Int COUNT = enumerate (threads); // The enumerate () method inherits from the threadgroup class, obtain all active worker threads in the thread group for (INT I = 0; I <count; I ++) based on the estimated value of the active thread) {// wait until all worker threads end. Try {threads [I]. join (); // wait until the worker thread ends} catch (interruptedexception ex) {ex. printstacktrace () ;}}/ *** internal class, working thread, responsible for extracting tasks from the work queue, run the * @ author sunnylocus */private class workthread extends thread {private int ID; Public workthread (int id) {// parent class constructor, add a thread to the current threadpool thread group super (Th Readpool. This, ID + ""); this. ID = ID;} public void run () {While (! Isinterrupted () {// The isinterrupted () method inherits from the Thread class to determine whether the thread is interrupted runnable task = NULL; try {task = gettask (ID ); // retrieve task} catch (interruptedexception ex) {ex. printstacktrace ();} // If gettask () returns NULL or the thread is interrupted when gettask () is executed, the thread if (task = NULL) return; try {task. run (); // run the task} catch (throwable t) {T. printstacktrace () ;}// end while} // end run} // end workthread}
2. Test class
Package COM. TDT. test; import COM. TDT. impl. ls. threadpool; public class threadpooltest {public static void main (string [] ARGs) throws interruptedexception {threadpool = new threadpool (3 ); // create a thread pool with three working threads. sleep (500); // sleep for 500 milliseconds, so that all worker threads in the thread pool can run // run the task for (INT I = 0; I <= 5; I ++) {// create 6 tasks threadpool.exe cute (createtask (I);} threadpool. waitfinish (); // wait until all tasks are completed threadpool. closepool (); // close the thread pool} Private Static runnable createtask (final int taskid) {return New runnable () {public void run () {// system. out. println ("task" + taskid + "start"); system. out. println ("Hello World"); // system. out. println ("task" + taskid + "end ");}};}}
Result:
Worker Thread 0 waiting for task... worker thread 1 waiting for task... worker thread 2 waiting for task... the worker Thread 0 starts to execute the task... hello world worker Thread 0 waiting for task... worker thread 1 starts to execute the task... hello world worker thread 1 waiting for task... worker thread 2 starts to execute the task... hello world worker thread 2 waiting for task... the worker Thread 0 starts to execute the task... hello world worker Thread 0 waiting for task... worker thread 1 starts to execute the task... hello world worker thread 1 waiting for task... worker thread 2 starts to execute the task... hello world worker thread 2 waiting for task...