1. What is a thread pool?
The thread pool is a form of multithreading that adds tasks to the queue during processing, and then automatically starts those tasks after the thread is created. Thread pool threads are all background threads.
2. Advantages of thread pool
Using a thread pool can effectively control the number of concurrent threads in the system, and when the system contains a large number of concurrent threads, there is a dramatic drop in performance and even a JVM crash, while the thread pool's maximum number of threads parameter can control the number of concurrent threads.
3, four kinds of thread pool
Newcachedthreadpool creates a cacheable thread pool that can flexibly reclaim idle threads if the thread pool length exceeds the processing needs, and creates a new thread if it is not recyclable.
Newfixedthreadpool creates a thread pool that controls the maximum number of concurrent threads, and the excess threads wait in the queue.
Newscheduledthreadpool creates a fixed-line pool that supports timed and recurring task execution.
Newsinglethreadexecutor creates a single threaded thread pool that performs tasks with only a single worker thread, ensuring that all tasks are executed in the specified order (FIFO, LIFO, priority).
4. Creation of thread pool
/** * @author baiyangshuxia * @time July 12, 2017 pm 10:15:47 * * Package Com;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;public class ThreadPool {public ThreadPool () {//Todo auto-generated constructor stub}public static void Main (string[] args) throws Exception {//Todo Aut O-generated method Stubexecutorservice Pool=executors.newfixedthreadpool (6); Runnable target= ()->{for (int i=0;i<100;i++) {System.out.println (Thread.CurrentThread (). GetName () + "The value of I is:" +i );}}; Pool.submit (target);p ool.submit (target);p ool.shutdown ();}}
5. To perform thread tasks using thread pooling
(1) Call the static factory method of the Ececutors class to create a Executorsservice object that represents a thread pool.
(2) Create an instance of the Runnable implementation class or Callable method class to perform the task as a thread.
(3) Call the Submit () method of the Executorservice object to submit the Runnable instance or callable instance.
(4) When you do not want to commit any tasks, call the shutdown () method of the Executorservice object to close the thread.
Java multi-thread thread pool