Thread pool
There is a cost to building a new thread because it involves interacting with the operating system. If you need to use a lot of short-life threads in your program, you should use a thread pool.
By handing the Runnable object to the thread pool for execution, a thread calls the run method, and when the run method exits, the thread does not die, but is prepared to service the next request in the pool.
Another reason to use the thread pool is to reduce the number of concurrent programming, creating a large number of threads that can greatly degrade performance and even crash the virtual machine, while using the thread pool can limit the total number of concurrent programming.
Creation and use of thread pools
While creating a thread pool object requires the use of an executor (executors), note that to add s, executor is an interface, and executors can create a thread pool object.
//创建一个不限数量的线程池,当执行一个任务的时候,如果有空闲线程用,会给它分配,如果没有空闲线程,就会创建一个新线程,空闲线程会被保留60秒ExecutorService executor = Executors.newCachedThreadPool();//创建一个具有固定数量的线程池,空闲线程也会被一直保留ExecutorService executor2 = Executors.newFixedThreadPool(5);//创建一个具有一个线程的线程池,由一个线程一个接一个的执行任务(感觉有点鸡肋)ExecutorService executor3 = Executors.newSingleThreadExecutor();//创建一个预定执行而构建的固定数量的线程池ExecutorService executor4 = Executors.newScheduledThreadPool(5);//创建一个用于预定执行而构建的只有一个线程的线程池ExecutorService executor5 = Executors.newSingleThreadScheduledExecutor();
The most common is the first three, the return is Executorservice object, Executorservice is also an interface.
If you want to see the number of threads in the current thread pool, you cannot use the Executorservice interface object to get it, you need to turn it into its subclasses, that is, the Threadpoolexecutor class object, about how to use it, in the previous article callable and future examples Address:
Https://www.cnblogs.com/Fill/p/9445908.html
5.Java thread pool creation and use