Summary of scenarios where java uses multithreading

In a high-concurrency website, multi-threading is essential. Let's talk about the role of multithreading in the program first.

1. Improve the response speed of front-end requests. When we execute a time-consuming method, the http request does not get a response or even times out. At this time, if the business allows data delay, we can use multithreading to process the time-consuming method. In this way, the front-end sends a request, and the back-end makes a thread to process the task, so that the main thread will not be blocked.

2, to reduce the pressure on the server. Including our web containers, such as tomcat, jetty, etc., as well as database servers, etc. Because we use multi-threading, and the thread pool size is limited, such as 30, then the number of links requesting the database at the same time is limited to 30, that is to say, there are only 30 threads that can execute methods at the same time, and the rest of the tasks are placed in our thread. the task queue, so that the database will not be overwhelmed by sudden requests. Of course, for alleviating the pressure on the database, it is more recommended to use message queues. Using message queues, we can save data for batch submission, but only using multi-threading is not easy to realize the process of saving data.

3. Improve processing capacity, increase performance, and make full use of server resources. If we want to load the data in three tables into the cache, the simplest way is to start one thread for one table, and sharing three threads to load the cache is much more efficient than using one thread to traverse the data of the three tables side by side.

Summary of usage scenarios

1. Use three threads to copy data from three tables at the same time, and then start a thread to update the data relationship of the three tables after the three threads are successfully copied.

2. The storage operation of historical data can be operated by multi-threading.

3. When initializing the cache, you can use threads to load the corresponding table data.

In short, using multi-threading is to make full use of cpu resources and improve program execution efficiency. When you find a business logic If the execution efficiency is particularly low and the time-consuming is particularly long, you can consider using multithreading. However, the time and order of which thread is executed by the CPU is uncertain. Even if the priority of the thread is set, the risk of using multi-threading is relatively large, and many unexpected problems will occur. You must be more familiar with the concept and construct more Different scenarios to test to be able to master!


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326066664&siteId=291194637