Java multithreading – thread pool

The cost of starting a new thread is relatively high. When a large number of threads with short lifetime need to be created in the program, the use of thread pool can improve the performance.

Similar to the database connection pool, the thread pool creates a large number of idle threads at system startup and. The program passes a runnable object to the thread pool, and the thread will start a thread to execute the run method of the object. After the execution of the run method, the thread will not die, but return to the thread pool to become idle and wait for the execution of the run method of the next runnable object.

Create thread pool

Java provides an executors factory class to generate thread pools. The factory class contains the following static factory methods to create thread pools:

The first three of the above five methods return an executorservice object, which represents a thread pool, which can execute the threads represented by runnable object and callable object. The latter two methods return a scheduledexecutorservice object, which is a subclass of executorservice and can execute thread tasks after a specified delay.

Execute thread task

Executorservice class provides a submit method to execute thread tasks and return execution results (if any); Scheduledexecutorservice additionally provides schedule, scheduleatfixedrate and scheduleatfixeddelay methods to delay the execution of thread tasks.

Close thread pool

When a thread pool is used up, you should call the shutdown () method of the thread pool, which will start the shutdown sequence of the thread pool. The thread pool that calls the shutdown () method will no longer accept new tasks, but will process the previously received tasks. When all tasks in the thread pool are completed, all threads in the pool will die. In addition, you can also call the shutdownnow() method of the thread pool to close the thread pool. This method will try to stop all executing tasks, suspend the processing of waiting tasks, and return to the waiting task list.

summary

The steps to execute thread tasks using thread pool are as follows:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>