Table of Contents
Preface
What is a thread pool
Why do we need a thread pool?
The role of the thread pool:
Disadvantages of single-threading
Say important things three times! ! !
The disadvantages are as follows:
Java thread pool
newSingleThreadExecutor
ScheduledExecutorService
newFixedThreadPool
相比new Thread,Java提供的四种线程池的好处在于:
阅读更多
相信自己,没有做不到的,只有想不到的
Home Backend Development PHP Tutorial Questions about thread pools that may be encountered in PHP interviews

Questions about thread pools that may be encountered in PHP interviews

Jul 20, 2018 am 09:46 AM
android java php

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();
Copy after login
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/imghw/default1.png" data-src="https://segmentfault.com/img/remote/1460000015702768" class="lazy" alt=" " title=" "><br></p><h5 id="newFixedThreadPool">newFixedThreadPool</h5><p><img src="/static/imghw/default1.png" data-src="https://segmentfault.com/img/remote/1460000015702769" class="lazy" alt=" " title=" "></p><h5><img src="/static/imghw/default1.png" data-src="https://segmentfault.com/img/remote/1460000015702770" class="lazy" alt=" " title=" "></h5><p   style="max-width:90%"><strong>newCachedThreadPool</strong></p><p><img src="/static/imghw/default1.png" data-src="https://segmentfault.com/img/remote/1460000015702771" class="lazy" alt=" " title=" "><br></p><h6 id="相比new-Thread-Java提供的四种线程池的好处在于">相比new Thread,Java提供的四种线程池的好处在于:</h6>
Copy after login
  • 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 of this Website
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

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

See all articles