Java Thread Pool

Source: Internet
Author: User

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. When t1 + T3 is much larger than t2, multithreading can significantly reduce the idle time of the processor unit and increase the throughput of the processor unit.

The thread pool is the container of a thread. Each time only the rated number of threads are executed, the thread pool is used to limit the number of execution threads in the system. The thread pool not only adjusts the time periods generated by T1 and T3, but also significantly reduces the number of created threads.

Why thread pool:

1) reduces the number of threads created and destroyed, and each worker thread can be reused to execute multiple tasks.

2) 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)

After Java, Java provides its own thread pool threadpoolexecutor class.

 

Introduction to threadpoolexecutor

 

The thread pool class is Java. util. Concurrent. threadpoolexecutor. The common constructor is as follows:

public ThreadPoolExecutor(              int corePoolSize,              int maximumPoolSize,              long keepAliveTime,              TimeUnit unit,              BlockingQueue<Runnable> workQueue) {}

Corepoolsize indicates the size of the reserved thread pool.

Maximumpoolsize indicates the maximum size of the thread pool.

KeepAliveTime refers to the timeout time for Idle threads to end.

Unit is an enumeration, indicating the unit of KeepAliveTime.

Workqueue indicates the queue for storing tasks.

 

A task is added to the thread pool using the execute (runnable) method. A task is a runnable object. The execution method of a task is the run () method of a runnable object.

 

The thread pool process is as follows:

1. When the thread pool is just created, there is no thread in it. The task queue is passed in as a parameter. However, even if there are tasks in the queue, the thread pool will not execute them immediately.

2. When you call the execute () method to add a task, the thread pool will make the following judgment:

A. If the number of running threads is smaller than corepoolsize, create a thread to run the task immediately;

B. If the number of running threads is greater than or equal to corepoolsize, put the task into the queue.

C. If the queue is full at this time and the number of running threads is smaller than maximumpoolsize, create a thread to run the task;

D. If the queue is full and the number of running threads is greater than or equal to maximumpoolsize, the thread pool will throw an exception and tell the caller "I can no longer accept the task ".

3. When a thread completes a task, it takes the next task from the queue for execution.

4. When a thread has nothing to do and exceeds a certain time (KeepAliveTime), the thread pool will judge that if the number of currently running threads is greater than corepoolsize, the thread will be stopped. Therefore, after all the tasks in the thread pool are completed, it will eventually contract to the corepoolsize.

This process indicates that the task will not be executed before the task is added. Assume that the queue size is 10, corepoolsize is 3, and maximumpoolsize is 6. When 20 tasks are added, the execution sequence is as follows: first, execute tasks 1, 2, and 3, then Task 4 ~ 13 is put into the queue. When the queue is full, tasks 14, 15, and 16 will be executed immediately, and tasks 17 ~ 20 will throw an exception. The final sequence is: 1, 2, 3, 14, 15, 16, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13.

The following is an example of a thread pool:

Public class testthreadpool {public static void main (string [] ARGs) {threadpoolexecutor threadpool = new threadpoolexecutor (3, 6, 5, timeunit. seconds, new queue blockingqueue <runnable> (); For (INT I = 1; I <= 20; I ++) {threadpool.exe cute (New threadpooltask ()); // threadpool. shutdown () ;}} creates the threadpooltask class: public class threadpooltask implements runnable {public void run () {try {system. out. println ("START task execution:" + attachdata); thread. sleep (100);} catch (exception e) {e. printstacktrace ();}}}

1. blockingqueue is just an interface. Common Implementation classes include linkedblockingqueue and arrayblockingqueue. The advantage of using linkedblockingqueue is that there is no size limit. In this case, because the queue is not full, execute () will not throw an exception, and the number of running threads in the thread pool will never exceed corepoolsize, so the KeepAliveTime parameter is meaningless.

2. The shutdown () method will not be blocked. After the shutdown () method is called, the main thread ends immediately, and the thread pool continues to run until all tasks are executed. If you do not call the shutdown () method, the thread pool will remain so that you can add new tasks at any time.

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.