Java multithreading Summary 5: principles and implementation of thread pools

Source: Internet
Author: User

1. Thread Pool introduction:
Multithreading technology mainly solves the problem of multiple threads in a processor unit. It can significantly reduce the idle time of the processor unit and increase the throughput of the processor unit.
Assume that the time required for a server to complete a task is T1 thread creation time, T2 thread execution time, and T3 thread destruction time.

If T1 + T3 is greater than t2, a thread pool can be used to improve server performance.
A thread pool consists of the following four basic components:
1. threadpool: used to create and manage thread pools, including creating thread pools, destroying thread pools, and adding new tasks;
2. Working thread (poolworker): a thread in the thread pool that is in the waiting state when no task exists and can be executed cyclically;
3. task: an interface that must be implemented by each task for the execution of tasks scheduled by the working thread. It mainly specifies the task entry and the final work after the task is executed, task execution status;
4. taskqueue: used to store unprocessed tasks. Provides a buffer mechanism.

The thread pool technology focuses on how to shorten or adjust T1 and T3 time to improve the performance of server programs. It arranges T1 and t3 in the start and end time periods or some idle time periods of the server program, so that when the server program processes customer requests, there will be no overhead of T1 and T3.
The thread pool not only adjusts the time periods generated by T1 and T3, but also significantly reduces the number of threads created. For example:
Assume that a server processes 50000 requests a day, and each request requires a separate thread. In the thread pool, the number of threads is generally fixed, so the total number of threads generated will not exceed the number of threads in the thread pool. If the server does not use the thread pool to process these requests, the total number of threads is 50000. Generally, the thread pool size is much smaller than 50000. Therefore, the server program that uses the thread pool does not waste time processing to create 50000 requests, thus improving efficiency.

In code implementation, the task interface is not implemented. Instead, the runnable object is added to the thread pool manager (threadpool), and the remaining tasks are completed by the thread pool manager (threadpool ).

 

Package mine. util. thread; import Java. util. using list; import Java. util. list;/*** thread pool class, thread MANAGER: Create thread, execute task, destroy thread, obtain basic thread information */public final class threadpool {// The default number of threads in the thread pool is 5 Private Static int worker_num = 5; // The work thread private workthread [] workthrads; // unprocessed task Private Static volatile int finished_task = 0; // task queue, used as a buffer, list thread unsafe private list <runnable> taskqueue = new queue list <runnable> (); Private Static threadp OOl threadpool; // create a thread pool private threadpool () {This (5);} // create a thread pool, worker_num is the number of worker threads in the thread pool. Private threadpool (INT worker_num) {threadpool. worker_num = worker_num; workthrads = new workthread [worker_num]; for (INT I = 0; I <worker_num; I ++) {workthrads [I] = new workthread (); workthrads [I]. start (); // enable threads in the thread pool} // single-State mode. Obtain the public static threadpool getthreadpool () {return getthreadpool (THR Eadpool. worker_num);} // in single-State mode, obtain a thread pool with the specified number of threads. worker_num (> 0) create a default number of worker threads for the thread pool // worker_num <= 0 public static threadpool getthreadpool (INT worker_num1) {If (worker_num1 <= 0) worker_num1 = threadpool. worker_num; If (threadpool = NULL) threadpool = new threadpool (worker_num1); Return threadpool;} // execute the task. In fact, it only adds the task to the task queue, when to execute a thread pool manager to determine public void execute (runnable task) {synchronized (taskqueue) {taskque UE. add (task); taskqueue. notify () ;}// execute tasks in batches. In fact, the task is only added to the task queue. When will the thread pool manager execute the public void execute (runnable [] task) {synchronized (taskqueue) {for (runnable T: task) taskqueue. add (t); taskqueue. notify () ;}// execute tasks in batches. In fact, the task is only added to the task queue. When will the thread pool manager execute the public void execute (list <runnable> task) {synchronized (taskqueue) {for (runnable T: task) taskqueue. add (t); taskqueue. Y () ;}// destroy the thread pool. This method ensures that all threads are destroyed only when all tasks are completed, Otherwise, the public void destroy () {While (! Taskqueue. isempty () {// if there are still tasks not completed, go to bed first. Try {thread. sleep (10);} catch (interruptedexception e) {e. printstacktrace () ;}// the worker thread stops working and is set to nullfor (INT I = 0; I <worker_num; I ++) {workthrads [I]. stopworker (); workthrads [I] = NULL;} threadpool = NULL; taskqueue. clear (); // clear the task queue} // return the number of worker threads. Public int getworkthreadnumber () {return worker_num;} // return the number of completed tasks, the number of completed tasks is only the number of tasks in the task queue. It is possible that the task is not actually executed. Public int getfini Shedtasknumber () {return finished_task;} // return the length of the task queue, that is, the number of unprocessed tasks. Public int getwaittasknumber () {return taskqueue. size () ;}// overwrite the tostring method and return the thread pool information: Number of working threads and number of completed tasks @ overridepublic string tostring () {return "workthread Number: "+ worker_num +" finished task number: "+ finished_task +" Wait task number: "+ getwaittasknumber ();}/*** internal class, worker thread */private class workthread extends thread {// whether the worker thread is valid to end the work Thread private Boolean isrunning = true;/** key. If the task queue is not empty, the task execution is taken out. If the task queue is empty, wait */@ overridepublic void run () {runnable r = NULL; while (isrunning) {// Note: If the thread is invalid, the run method ends naturally, and synchronized (taskqueue) is useless for this thread) {While (isrunning & taskqueue. isempty () {// The queue is empty. Try {taskqueue. wait (20);} catch (interruptedexception e) {e. printstacktrace () ;}} if (! Taskqueue. isempty () r = taskqueue. Remove (0); // retrieve task} If (R! = NULL) {R. run (); // execute the task} finished_task ++; r = NULL ;}/// stop the job, so that the thread naturally runs the run method and ends the public void stopworker () {isrunning = false ;}}}

 

Test code:

Package mine. util. thread; // test the thread pool public class testthreadpool {public static void main (string [] ARGs) {// create a thread pool threadpool T = threadpool.getthreadpool(3100000000t.exe cute (New runnable [] {new task (), new task (), new task () extends extends t.exe cute (New runnable [] {new task (), new task (), new task ()}); system. out. println (t); T. destroy (); // All threads are executed to destorysystem. out. println (t);} // task class static class task implements runnable {Private Static volatile int I = 1; @ overridepublic void run () {// execute the task system. out. println ("task" + (I ++) + "finished ");}}}

 

Running result:

Workthread number: 3 finished task number: 0 wait Task Number: 6
Task 1 Completed
Task 2 completed
Task 3 completed
Task 4 completed
Task 5 completed
Task 6 completed
Workthread number: 3 finished task number: 6 wait Task Number: 0

Analysis: As there is no task interface, any custom task can be input, therefore, the thread pool cannot accurately determine whether the task is actually completed (the run method of the task is actually completed), but only knows that the task has been out of the task queue, execution in progress or completed.

2. Introduction to the thread pool provided in the Java Class Library:

The thread pool provided by Java is more powerful. I believe that I can understand the working principle of the thread pool and look at the thread pool in the class library.

For more details, see JDK help or JDK source code...

Reference: http://hi.baidu.com/obullxl/blog/item/ee50ad1ba8e8ff1f8718bf66.html

Related Article

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.