[Thread pool of java thread-related knowledge] What is a thread pool?

Posted by gofer on Wed, 14 Aug 2019 08:45:17 +0200

What is thread pool and how to use it?

Thread pool is to put multiple thread objects into a container, when used, it can take threads directly in the pool instead of new threads, which saves the time of opening sub-threads and improves the efficiency of code execution.

In JDK's java.util.concurrent.Executors, static methods for generating multiple thread pools are provided. (a variety of convenient factory methods)

ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();  

ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(4);  

ScheduledExecutorService newScheduledThreadPool = Executors.newScheduledThreadPool(4);  
  
ExecutorService newSingleThreadExecutor = Executors.newSingleThreadExecutor();

Then call their execute method.

What are the common thread pools?

New Single ThreadExecutor: Create a single-threaded thread pool that ensures that all tasks are executed in the order in which they are submitted.
New Fixed ThreadPool: Create a fixed-size thread pool, creating a thread every time a task is submitted, until the thread reaches the maximum size of the thread pool.
New Cached ThreadPool: Create a cacheable thread pool that does not limit the size of the thread pool. The size of the thread pool depends entirely on the maximum thread size that the operating system (or JVM) can create.
New Scheduled ThreadPool: Create an infinite thread pool that supports the need to perform tasks on a regular and periodic basis.

The benefits of using thread pools?

First, reduce resource consumption. Reduce the consumption of thread creation and destruction by reusing created threads.
Second, improve the response speed. When a task arrives, it can be executed immediately without waiting for the thread to be created.
Third, improve the manageability of threads. Threads are scarce resources. If created unrestrictedly, it will not only consume system resources, but also reduce the stability of the system. Thread pool can be used for uniform allocation, tuning and monitoring.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/*
    Thread pool: provided after JDK 1.5
    java.util.concurrent.Executors:A factory class for thread pools to generate thread pools
    Executors Static methods in classes:
        static ExecutorService newFixedThreadPool(int nThreads) Create a thread pool with a fixed number of reusable threads
        Parameters:
            int nThreads:Create the number of threads contained in the thread pool
        Return value:
            ExecutorService Interface, the return is the implementation class object of ExecutorService interface, we can use ExecutorService interface to receive (interface-oriented programming)
    java.util.concurrent.ExecutorService:Thread pool interface
        Used to fetch threads from the thread pool, call the start method, and perform threading tasks
            submit(Runnable task) Submit a Runnable task for execution
        Method of closing/destroying thread pool
            void shutdown()
    Use steps of thread pool:
        1.Produce a thread pool with a specified number of threads using the static method newFixedThreadPool provided in the factory class Executors
        2.Create a class, implement the Runnable interface, override the run method, and set thread tasks
        3.Call the method submit in ExecutorService, pass the thread task (implementation class), open the thread, and execute the run method.
        4.Call the method shutdown in ExecutorService to destroy the thread pool (not recommended)
 */
public class Demo01ThreadPool {
    public static void main(String[] args) {
        //1. Produce a thread pool with a specified number of threads using the static method newFixedThreadPool provided in the factory class Executors of the thread pool
        ExecutorService es = Executors.newFixedThreadPool(2);
        //3. Call the method submit in ExecutorService, pass the thread task (implementation class), open the thread, and execute the run method.
        es.submit(new RunnableImpl());//pool-1-thread-1 creates a new thread execution
        //Thread pool will always open, after using the thread, will automatically return the thread to the thread pool, the thread can continue to use.
        es.submit(new RunnableImpl());//pool-1-thread-1 creates a new thread execution
        es.submit(new RunnableImpl());//pool-1-thread-2 creates a new thread execution

        //4. Call the method shutdown in ExecutorService to destroy the thread pool (not recommended)
        es.shutdown();

        es.submit(new RunnableImpl());//Thread pools are missing and threads cannot be retrieved by throwing exceptions
    }
}
/*
    2.Create a class, implement the Runnable interface, override the run method, and set thread tasks
 */
public class RunnableImpl implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"Create a new thread execution");
    }
}

Topics: Java JDK jvm Programming