Thread pool of java learning thread

Posted by cyberrate on Sat, 15 Jan 2022 08:06:38 +0100

2.1 overview of thread pool idea

When we use threads, we create a thread, which is very easy to implement, but there will be a problem:

If there are a large number of concurrent threads and each thread executes a task for a short time, the efficiency of the system will be greatly reduced because it takes time to create and destroy threads frequently.

So is there a way to make threads reusable, that is, after executing a task, they can continue to execute other tasks without being destroyed?

In Java, this effect can be achieved through thread pool. Today, let's talk about java thread pool in detail.

2.2 thread pool concept

  • Thread pool: in fact, it is a container containing multiple threads, in which threads can be used repeatedly, eliminating the operation of frequently creating thread objects and consuming too many resources without repeatedly creating threads.

Since many operations in the thread pool are related to optimizing resources, we will not repeat them here. Let's understand the working principle of thread pool through a diagram:

Rational utilization of thread pool can bring three benefits:

  1. Reduce resource consumption. The number of threads created and destroyed is reduced. Each worker thread can be reused and can perform multiple tasks.

  2. Improve response speed. When the task arrives, the task can be executed immediately without waiting for the thread to be created.

  3. Improve thread manageability. You can adjust the number of work line threads in the thread pool according to the affordability of the system to prevent the server from getting tired due to excessive memory consumption (each thread needs about 1MB of memory. The more threads are opened, the more memory will be consumed, and finally crash).

2.3 use of thread pool

The top-level interface of thread pool in Java is Java util. concurrent. Executor, but strictly speaking, executor is not a thread pool, but just a tool for executing threads. The real thread pool interface is Java util. concurrent. ExecutorService.

Configuring a thread pool is complex, especially when the principle of thread pool is not very clear, it is likely that the configured thread pool is not better, so in Java util. concurrent. Executors thread factory class provides some static factories to generate some common thread pools. Officials recommend using the executors project class to create thread pool objects.

There is a method in the Executors class to create a thread pool, as follows:

  • public static ExecutorService newFixedThreadPool(int nThreads): returns the thread pool object. (a bounded process pool is created, that is, the maximum number of threads in the pool can be specified)

If a thread pool ExecutorService object is obtained, how to use it? Here, a method to use the thread pool object is defined as follows:

  • public Future<?> Submit (runnable task): get a thread object in the thread pool and execute it

    Future interface: used to record the results generated after the execution of thread tasks. Thread pool creation and use.

To use thread objects in the thread pool:

  1. Create a thread pool object.

  2. Create a Runnable interface subclass object. (task)

  3. Submit the Runnable interface subclass object. (take task)

  4. Close the thread pool (not normally).

Runnable implementation class code:

public class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("I want a coach");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Here comes the coach: " + Thread.currentThread().getName());
        System.out.println("Teach me to swim,After handing it in, the coach returned to the swimming pool");
    }
}

Thread pool test class:

public class ThreadPoolDemo {
    public static void main(String[] args) {
        // Create thread pool object
        ExecutorService service = Executors.newFixedThreadPool(2);//Contains 2 Thread objects
        // Create Runnable instance object
        MyRunnable r = new MyRunnable();
​
        //How to create thread objects yourself
        // Thread t = new Thread(r);
        // t.start(); --->  Call run() in MyRunnable
​
        // Gets the thread object from the thread pool and then calls run() in MyRunnable.
        service.submit(r);
        // Get another thread object and call run() in MyRunnable
        service.submit(r);
        service.submit(r);
        // Note: after the submit method is called, the program does not terminate because the thread pool controls the closing of threads.
        // The used thread is returned to the thread pool
        // Close thread pool
        //service.shutdown();
    }
}

Topics: Java