search
HomeBackend DevelopmentPHP TutorialQuestions about thread pools that may be encountered in PHP interviews

This article introduces to you the issues about thread pools that may be encountered during interviews. It has certain reference value. Friends in need can refer to it.

Preface

We often encounter questions about multi-threading and thread pools during interviews. How to answer them? Today, we will learn about the thread pool in Java.

What is a thread pool

The thread pool refers to creating a collection of threads during the initialization of a multi-threaded application, and then reusing these threads when new tasks need to be performed instead of creating a new thread. . The number of threads in a thread pool usually depends entirely on the amount of available memory and the needs of the application. However, it is possible to increase the number of available threads. Each thread in the thread pool is assigned a task. Once the task has been completed, the thread returns to the pool and waits for the next assigned task.

To put it bluntly, it is a thread collection that executes multiple threads for an application.

Why do we need a thread pool?

Using the thread pool, I have currently solved the problem:

  • Use the thread pool to obtain multiple covers in a video, thereby saving money. It took some time and resources

  • The background server does not support multiple image uploads. Use the thread pool to upload multiple images, thereby reducing the upload time

The rendering is as follows:


Questions about thread pools that may be encountered in PHP interviews

Before uploading: 9 pictures will take at least 3 seconds, use After thread pool optimization, 9 pictures take 1 second.

Using threads in multi-threaded applications is necessary for the following reasons:

  • 1. Reduces the number of threads created and destroyed times, each worker thread can be reused to perform multiple tasks.

  • 2. You can adjust the number of working threads in the thread pool according to the system's capacity to prevent the server from being exhausted due to excessive memory consumption (each thread requires About 1MB of memory. The more threads are opened, the more memory is consumed, and eventually it crashes).

  1. Thread pools improve an application's response time. Since the threads in the thread pool are ready and waiting to be assigned tasks, the application can use them directly without creating a new thread.

  2. The thread pool saves the CLR the overhead of creating a complete thread for each short-lived task and can reclaim resources after the task is completed.

  3. The thread pool optimizes thread time slices based on the processes currently running in the system.

  4. Thread pool allows us to start multiple tasks without setting properties for each thread.

  5. The thread pool allows us to pass an object reference containing state information for the program parameters of the task being executed.

  6. The thread pool can be used to solve the problem of limiting the maximum number of threads to handle a specific request.

Appease the many-year-old Fafafa

The role of the thread pool:

The role of the thread pool is to limit execution in the system The number of threads.
According to the system environment, the number of threads can be set automatically or manually to achieve the best operation effect; less will waste system resources, and more will cause system congestion and inefficiency. Use the thread pool to control the number of threads, and other threads wait in line. After a task is executed, the frontmost task in the queue is taken and execution begins. If there is no waiting process in the queue, this resource of the thread pool is waiting. When a new task needs to be run, if there are waiting worker threads in the thread pool, it can start running; otherwise, it enters the waiting queue.

Disadvantages of single-threading

Give me an example

new Thread(new Runnable() {

@Override
public void run() {
   paPaPaYourGridFriend();
}
}).start();
Say important things three times! ! !

If you are still using new Thread to perform an asynchronous task, so you are Out!
If you are still using new Thread to perform an asynchronous task, so you are Out!
If you are still using new Thread to perform an asynchronous task, so you are Out!

The disadvantages are as follows:
  • a. Each time new Thread creates an object, the performance is poor.

  • b. Threads lack unified management, and there may be unlimited new threads, competing with each other, and may occupy too many system resources, causing crashes or OOM.

  • c. Lack of more functions, such as scheduled execution, periodic execution, and thread interruption.

Java thread pool

1. newSingleThreadExecutor

Create a single-threaded thread pool. This thread pool has only one thread working, which is equivalent to a single thread executing all tasks serially. If the only thread ends abnormally, a new thread will replace it. This thread pool ensures that all tasks are executed in the order in which they are submitted.

2.newFixedThreadPool

创建固定大小的线程池。每次提交一个任务就创建一个线程,直到线程达到线程池的最大大小。线程池的大小一旦达到最大值就会保持不变,如果某个线程因为执行异常而结束,那么线程池会补充一个新线程。

3. newCachedThreadPool

创建一个可缓存的线程池。如果线程池的大小超过了处理任务所需要的线程,

那么就会回收部分空闲(60秒不执行任务)的线程,当任务数增加时,此线程池又可以智能的添加新线程来处理任务。此线程池不会对线程池大小做限制,线程池大小完全依赖于操作系统(或者说JVM)能够创建的最大线程大小。

4.newScheduledThreadPool

创建一个大小无限的线程池。此线程池支持定时以及周期性执行任务的需求。

newSingleThreadExecutor
  private void TextnewSingleThreadExecutor(){
        ExecutorService pool = Executors. newSingleThreadExecutor();

        MyTask1 task1 =   new MyTask1();
        MyTask2 task2 =   new MyTask2();
        MyTask3 task3 =   new MyTask3();

//        pool.execute(task1);
//        pool.execute(task2);
//        pool.execute(task3);

        new Thread(task1).start();
        new Thread(task2).start();
        new Thread(task3).start();
    }

    private class MyTask1 implements Runnable{
        @Override
        public void run() {
            //循环输出
            for(int i = 0; i <h5 id="ScheduledExecutorService">ScheduledExecutorService</h5><p><img src="/static/imghwm/default1.png" data-src="https://segmentfault.com/img/remote/1460000015702768?x-oss-process=image/resize,p_40" class="lazy" alt=" " title=" "><br></p><h5 id="newFixedThreadPool">newFixedThreadPool</h5><p><img src="/static/imghwm/default1.png" data-src="https://segmentfault.com/img/remote/1460000015702769?x-oss-process=image/resize,p_40" class="lazy" alt=" " title=" "></p><h5><img src="/static/imghwm/default1.png" data-src="https://segmentfault.com/img/remote/1460000015702770?x-oss-process=image/resize,p_40" class="lazy" alt=" " title=" "></h5><p   style="max-width:90%"><strong>newCachedThreadPool</strong></p><p><img src="/static/imghwm/default1.png" data-src="https://segmentfault.com/img/remote/1460000015702771?x-oss-process=image/resize,p_40" class="lazy" alt=" " title=" "><br></p><h6 id="相比new-Thread-Java提供的四种线程池的好处在于">相比new Thread,Java提供的四种线程池的好处在于:</h6>
  • a. 重用存在的线程,减少对象创建、消亡的开销,性能佳。

  • b. 可有效控制最大并发线程数,提高系统资源的使用率,同时避免过多资源竞争,避免堵塞。

  • c. 提供定时执行、定期执行、单线程、并发数控制等功能。

线程池真的是太好用了,如果在项目中通过线程池管理线程,,你将会发现其中的诸多优势!

阅读更多

20+个很棒的Android开源项目

2018年Android面试题含答案--适合中高级(下)一份完整的Android Studio搭建Flutter教程[](http://mp.weixin.qq.com/s?__b...

深入了解JAVA的线程中断方法经验之总结

子线程为什么不能更新UI线程详解

相信自己,没有做不到的,只有想不到的

相关推荐:

php如何连接数据库的方法

PHP中http的数据库是如何进行验证登录

The above is the detailed content of Questions about thread pools that may be encountered in PHP interviews. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use