Principle analysis of Java thread pool

I recently learned the "Java Concurrent Programming Practice" of geek time, and I have a new understanding of java thread pool and my own understanding, as well as some ideas, such as whether I can design a distributed thread pool, whether I can design a thread pool that can dynamically modify parameters, and whether I can design a thread pool that can monitor the execution of tasks in real time, Therefore, I hope to make progress with you and make progress together.

First of all, I would like to talk about my understanding of thread pool in five years of programming. I have learned code for one year and understood the calculator in C language. I have been exposed to object-oriented programming ideas for two years. I have been exposed to many books and blogs. Most voices say that Java, the corresponding language, is relatively representative, The so-called object-oriented programming is that you have to write code facing your object. Ha ha, this is obviously a joke. In fact, the code is not written in line by line, but needs to have module lines like building blocks. Define the corresponding function modules, functions and responsibilities to specific function classes. First, let's understand the benefits of object-oriented, All theories and new technologies have needs first and then solutions. Unlike learning, learning often starts with learning formulas, and then solving type problems according to the formulas, repeated practice, multiple-choice questions and application questions. Therefore, many educated students will have a misunderstanding in learning technology. First understand the conceptual formulas, and then understand the application scenarios, It's like buying an electric screwdriver and trying to screw it at home 🤏 Everything has been screwed up once. In fact, it doesn't need to be repaired, so we should first forget the solution, first find the problem, first think about the methodology to solve the problem, then look at the solutions that have been implemented, and then according to the solutions that have been implemented, Worldly wisdom teachers that it is better for reputation to fail conventionally than to succeed unconventionally, Let's follow this idea to look at this problem and think about it 🤔, The style of process oriented code writing cannot be maintained when the amount of code is large, and it is difficult to expand. For example, I want to round up the result for the addition, subtraction, multiplication and division of a calculator. Is it difficult? Therefore, object-oriented (OOP) programming languages such as Java can derive many design principles and design patterns according to its language characteristics of encapsulation, inheritance and polymorphism, such as Open Close principle and single responsibility. These programming ideas need to reach the accumulation of a certain amount of code, which can not be described.

Let's get back to business. We should have heard of Java multithreading and use it very little, because most of the development work of the system is web application development under the spring framework ecology, The mainstream server Tomcat is multi-threaded. We only need to write the service under the system of SpringMvc. As long as we note that spring beans are single instance by default (that is, the objects of Sprint managed beans are globally unique by default, and the level can be modified of course), that is, we can no longer define the constant of class level in the service, Most programmers do not need to consider multi-threaded development, but there are also a few application scenarios. For example, for some batch data processing tasks, a thread will be created to get rid of the synchronous waiting constraints of the main thread, skip processing and carry out other work. Then the system has used the spring container to manage objects, reducing the waste of resources in creating objects, However, creating a thread is not a simple object, which is a waste of resources. The specific logic will be explained in detail in the next article.

There are two ways to create a thread:

public class TestThread extends Thread {
    @Override
    public void run() {
        System.out.println("test");
    }

    public static void main(String[] args) {
        TestThread testThread = new TestThread();
        testThread.start();
    }
}

 

public class TestThread implements Runnable {
    @Override
    public void run() {
        System.out.println("test");
    }

    public static void main(String[] args) {
        TestThread testThread = new TestThread();
        Thread thread = new Thread(testThread);
        thread.start();
    }
}

When a large number of thread tasks are created in the system, the system resources will be exhausted. How to solve this problem, we should first consider two ideas:

First point: unified thread management

Second point: control thread execution

To solve these two problems, we need a thread container to store thread tasks and execute them according to the set rules. We will think of pooling technology, which is to create threads and put them in a thread pool, and then the thread pool will execute according to the set rules. At this time, you will look at the source code of the thread pool, Then I found that there is no corresponding method to apply for resources. In fact, the technology of thread pool is the consumer model. Specifically, I wrote a demo code:

 

public class MyThreadPool {
    //Blocked queues are used to store thread tasks that need to be executed
    BlockingQueue<Runnable> workQueue;

    List<WorkerThread> threads = new ArrayList<>();
    ThreadFactory threadFactory;
    MyThreadPool(int poolSize, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
        this.workQueue = workQueue;
        this.threadFactory = threadFactory;
        for (int i = 0; i < poolSize; i++) {
            WorkerThread workerThread = new WorkerThread();
            workerThread.start();
            threads.add(workerThread);
        }
    }

    void execute(Runnable task){
        try {
            workQueue.put(task);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    class WorkerThread extends Thread {
        @Override
        public void run() {
            while (true) {
                Runnable task = null;
                try {
                    task = workQueue.take();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                task.run();
            }
        }
    }
}
public class MyThreadPoolApplication {
    public static void main(String[] args) {
        MyThreadPool myThreadPool = new MyThreadPool(5, new ArrayBlockingQueue<Runnable>(2, false), r -> new Thread(r, "thread :" + Thread.currentThread().getId()));
        for (int i = 0; i < 50; i++) {
            myThreadPool.execute(() -> {
                System.out.println(Thread.currentThread().getName() + ":Hello");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

    }
}

There is a blocking queue in the code. The workQueue is used to store the submitted thread task. In fact, it is a specific class that passes a run method. You can think of it as storing a function function. Generally, we recommend using a bounded blocking queue, which can define an implementation class of the function function of handle, Specifies how to execute when the bounded queue is full.

There is also a work queue in the code, which is the real working thread in the thread pool. The number of working threads is initialized according to the defined thread pool size, and a single working thread is started to block the execution of tasks. Of course, ThreadPoolThread will be much more complex than this, but the principle is the same. It is a consumer model.

The prevention of executing thread tasks is execute, which is only used to add tasks to the blocked queue.

 

Reference: geek time "Java Concurrent Programming Practice"

 

Keywords: Java MySQL thread pool

Added by river001 on Sat, 19 Feb 2022 21:11:42 +0200