"Pool" technology is very familiar to us a concept, it is introduced in order to improve the performance of some key nodes of the system in some scenarios, the most typical example is the database connection pool, JDBC is a service supply interface (SPI), the specific database connection implementation class is implemented by different vendors, Database connection establishment and destruction are very time-consuming resource operations, in order to query a database record, the most primitive process is to establish a connection, send query statements, return query results, destroy the connection, if it is just a simple query statement, Then the possibility of establishing a connection and destroying the connection two steps has accounted for the vast majority of all resource time consumption, and such inefficiency is obviously unacceptable. For this process to improve efficiency through some means, so think of minimizing the creation and destruction of connection operations, because the connection is stateless relative to the query, do not have to regenerate the destruction every time, we can maintain these channels for the next query to use, the maintenance of these pipelines to the "pool."
The thread pool is also a pool similar to a database connection pool, instead of just swapping the objects in the pool for threads. Threads are concepts introduced for multitasking, where each thread executes a task at any time, and multithreading is used if multiple tasks are to be executed concurrently. Each thread has its own life cycle, which is created as the beginning of the destruction as the end. For example, the two-thread-running phase accounts for a different proportion of the entire life cycle, and a thread with a small proportion of the running phase can consider it to be inefficient, and the following thread thinks it is running efficiently. In most scenarios, it is better to conform to the thread-running pattern above the graph, such as our common Web services, database services, and so on. In order to improve the efficiency of the thread pool, its core idea is to make the running phase as long as possible, the arrival of each task is not to re-establish the destruction of the thread, but re-use the previously established thread to perform the task.
One option is to set up a certain number of threads on the system startup and do a good job of thread maintenance, and once a task arrives, remove an idle thread from the thread pool to perform the task. The principle sounds clearer, but in reality for a thread, once the Start method is called, the task is run until the task is completed, and then the JVM recycles the thread object, so that the thread does not destroy it? Yes, so you need to change the thinking angle so that these threads start out with an infinite loop to perform the specified task, the following will focus on how to implement the thread pool.
The properties of a thread pool contain at least the number of initialized threads, the thread array, and the task queue. The number of initialization threads refers to the number of threads initialized by the thread pool, which holds all the threads in the thread pools, and the task queue refers to all the tasks that are added to the thread-pool waiting to be processed. For example, there are two threads in the thread pool, and the job of the pool thread is to continually cycle through the task queue for tasks that need to be performed, and if so, to process and move out of the task queue. So it can be said that the task of all threads in the thread pool is to constantly detect the task queue and continuously execute the tasks in the queue.
Looking at one of the simplest and most coarse thread pool implementations, using a thread pool is simply instantiating an object, the constructor creates the appropriate number of threads and starts the thread, the thread that starts the infinite loop detects the task queue, and executes method execute () simply adds the task to the task queue. One thing to note is that all tasks must implement the Runnable interface, which is the contract of the thread pool's task queue with the worker thread, the JUC Toolkit author Doug Lea, the great God, then stipulated that the worker thread detects the task queue and calls the queue's run () method, If you re-write a thread pool yourself, you can define a different task interface yourself. A complete thread pool is not as simple as the following example, it needs to provide startup, destroy, increase worker thread policies, maximum number of worker threads, access to various states, and so on, and worker threads cannot always do useless loops, need to use wait for task queue, notify optimization or task queue instead of blocking queue.
Public final class ThreadPool {
private final int worker_num;
Private workerthread[] workerthrads;
Private list<runnable> Taskqueue = new linkedlist<runnable> ();
private static ThreadPool ThreadPool;
Public ThreadPool (int worker_num) {
This.worker_num = Worker_num;
Workerthrads = new Workerthread[worker_num];
for (int i = 0; i < Worker_num; i++) {
Workerthrads[i] = new Workerthread ();
Workerthrads[i].start ();
}
}
public void execute (Runnable task) {
Synchronized (taskqueue) {
Taskqueue.add (Task);
}
}
Private class Workerthread extends Thread {
public void Run () {
Runnable r = null;
while (true) {
Synchronized (taskqueue) {
if (!taskqueue.isempty ()) {
r = Taskqueue.remove (0);
R.run ();
}
}
}
}
}
}
Through the above has been clear the thread pool principle, but does not advocate the re-build wheel behavior, because the thread pool processing is not easy to create deadlock problem, while the line Cheng state synchronization operation improper can also lead to unexpected problems, in addition there are many other concurrency problems, Unless you are an experienced concurrent programmer, you can minimize possible errors. We directly use the JDK's JUC toolkit, which is an excellent concurrent program tool written by Doug Lea, and the single thread pool has provided many kinds of thread pools, and the actual development is based on the need to select the appropriate pool of threads.
Java concurrency-thread pool principle