Java Thread Pool usage instructions
A Brief introduction
The use of threads is of paramount importance in Java, where the use of thread pools is very rudimentary in the JDK version of jdk1.4. The situation has changed a lot since the jdk1.5. Jdk1.5 later joined the Java.util.concurrent package, which focuses on Java threads and the use of thread pools. Provides a great deal of help with the problem of threading in development.
Two: Thread pool
The role of the thread pool:
The thread pool function is to limit the number of threads executing in the system.
According to the environment of the system, the number of threads can be set automatically or manually to achieve the best performance; less waste of system resources, more caused by the system congestion efficiency is not high. Use the thread pool to control the number of threads and other threads to wait. A task is completed, and then the first task from the queue is executed. If there is no waiting process in the queue, this resource of the thread pool is waiting. When a new task needs to run, it can start running if there are waiting worker threads in the thread pool, otherwise enter the wait queue.
Why use a thread pool:
1. Reduces the number of times a thread is created and destroyed, and each worker thread can be reused to perform multiple tasks.
2. You can adjust the number of threads in the thread pool according to the endurance of the system, prevent the server from being exhausted because it consumes too much memory (approximately 1MB of memory per thread, the more threads open, the more memory is consumed and the last crashes).
The top interface of the thread pool in Java is executor, but strictly speaking, executor is not a thread pool, but a tool for executing threads. The real thread pool interface is executorservice.
Some of the more important classes:
Executorservice Executor (execution) Interface |
A true thread pool interface. |
Scheduledexecutorservice Scheduled (scheduled) |
can be similar to Timer/timertask to solve problems that require repetitive execution of tasks. |
Threadpoolexecutor |
The default implementation of Executorservice. |
Scheduledthreadpoolexecutor |
Inheriting Threadpoolexecutor's Scheduledexecutorservice interface implementation, the class implementation of periodic task scheduling. |
Java thread pool usage instructions