国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
2.2.2.newSingleThreadExector
2.2.3.newCachedThreadPool
Home Java JavaBase Java explains ThreadPool thread pool

Java explains ThreadPool thread pool

Mar 03, 2021 am 10:36 AM
java

Java explains ThreadPool thread pool

ThreadPool thread pool

  • 1. Advantages of thread pool
    • ##1.1. Introduction
    • 1.2. Why to use thread pool
  • 2. Use of thread pool
    • 2.1. Architecture description
    • 2.2.Three major methods of thread pool
      • 2.2.1.newFixedThreadPool(int) method
      • 2.2.2.newSingleThreadExector
      • 2.2.3.newCachedThreadPool
  • 3.The underlying principle of ThreadPoolExecutor
  • 4. The seven important parameters of the thread pool
(Related free learning recommendations:

java basic tutorial)

1. Advantages of thread pool

1.1. Introduction

Similar to the database thread pool, if there is no database connection pool, then new is required every time the database connection pool is used to obtain the connection pool. Repeated connection and release operations will consume a lot of system resources. We can use the database connection pool and directly get the connection pool from the pool.

Similarly, before there was a thread pool, we also obtained threads through new Thread.start(). Now we don't need new, so that we can achieve reuse and make our system more efficient.

1.2. Why use thread pool

Example:

    10 years ago single-core CPU computer, fake multi-threading, like The circus clown plays with multiple balls, and the CPU needs to switch back and forth.
  • Now is a multi-core computer. Multiple threads run on independent CPUs, so there is no need to switch and it is highly efficient.

Advantages of the thread pool:

The thread pool only needs to control the number of running threads and put the tasks into the queue during processing. , and then start these tasks after the threads are created. If the number of threads exceeds the maximum number, the excess threads will queue up and wait for other threads to finish executing, and then take the tasks out of the queue for execution.

Its main features are:

  • Thread reuse
  • Control the maximum number of concurrencies
  • Management thread
Advantages:

  • First: Reduce resource consumption. Reduce the overhead caused by thread creation and destruction by reusing already created threads.
  • Second: Improve response speed. When a task arrives, the task can be executed immediately without waiting for thread creation.
  • Third: Improve the manageability of threads. Threads are scarce resources. If they are created without restrictions, they will not only consume system resources, but also reduce the stability of the system. The thread pool can be used for unified allocation, tuning and monitoring.

2. Use of thread pool

2.1. Architecture description

Executor What is a framework?

This is how it is described in Java Doc

An object that executes submitted Runnable tasks. This interface provides a way of decoupling task submission from the mechanics of how each task will be run, including details of thread use, scheduling, etc. An Executor is normally used instead of explicitly creating threads.

Object that executes submitted Runnable tasks. This interface provides a mechanism to submit tasks and how to run each task, including details of thread usage, scheduling, etc. It is common to use an Executor instead of explicitly creating threads.

The thread pool in Java is implemented through the Executor framework, which uses the classes Executor, Executors, ExecutorService, and ThreadPoolExecutor.

The interface we commonly use is the ExecutorService sub-interface, Executors are tool classes for threads (tool classes similar to arrays Arrays, tool classes Collections for collections). ThreadPoolExecutor is the focus of these classes. We can get the ThreadPoolExecutor thread pool through the auxiliary tool class Executors
Java explains ThreadPool thread pool A more detailed introduction to each class is as follows:

Executor interfaces for all thread pools , there is only one method. This interface defines the way to execute Runnable tasks
ExecutorService adds the behavior of Executor, which is the most direct interface of Executor implementation class. This interface definition provides services for Executor
Executors thread pool factory class provides a series of factory methods for creating thread pools. The returned thread pools all implement ScheduledExecutorService: scheduled scheduling interface.
AbstractExecutorService execution framework abstract class.

ThreadPoolExecutor The specific implementation of the thread pool in JDK. Various commonly used thread pools are implemented based on this class.

2.2. Three major methods of thread pool

2.2.1.newFixedThreadPool(int) method

Exectors.newFixedThreadPool(int) -->

Good performance in executing long-term tasks, create a Thread pool, a pool has N fixed threads, and a fixed number of threads

	public?static?void?main(String[]?args)?{
		//一池5個(gè)受理線程,類似一個(gè)銀行5個(gè)受理窗口。不管你現(xiàn)在多少個(gè)線程,都只有5個(gè)
		ExecutorService?threadPool=Executors.newFixedThreadPool(5);?
		
		try?{
			//模擬有10個(gè)顧客過來銀行辦理業(yè)務(wù),目前池子里面有5個(gè)工作人員提供服務(wù)。
			for(int?i=1;i{
					System.out.println(Thread.currentThread().getName()+"\t?辦理業(yè)務(wù)");
				});
			}
		}?catch?(Exception?e)?{
			//?TODO:?handle?exception
		}finally{
			threadPool.shutdown();
		}	
	}

Java explains ThreadPool thread pool
You can see the execution results. There are 5 threads in the pool, which is equivalent to 5 staff members providing external services and handling business. In the picture, window No. 1 handles business twice, and the bank's acceptance window can be reused multiple times. It’s not necessarily that everyone handles it twice, but whoever handles it faster will handle more.

When we add a 400ms delay during thread execution, we can see the effect

public?static?void?main(String[]?args)?{
		//一池5個(gè)受理線程,類似一個(gè)銀行5個(gè)受理窗口。不管你現(xiàn)在多少個(gè)線程,都只有5個(gè)
		ExecutorService?threadPool=Executors.newFixedThreadPool(5);?
		
		try?{
			//模擬有10個(gè)顧客過來銀行辦理業(yè)務(wù),目前池子里面有5個(gè)工作人員提供服務(wù)。
			for(int?i=1;i{
					System.out.println(Thread.currentThread().getName()+"\t?辦理業(yè)務(wù)");
				});
				try?{
					TimeUnit.MILLISECONDS.sleep(400);
				}?catch?(Exception?e)?{
					//?TODO:?handle?exception
					e.printStackTrace();
				}
			}
		}?catch?(Exception?e)?{
			//?TODO:?handle?exception
		}finally{
			threadPool.shutdown();
		}	
	}

Java explains ThreadPool thread pool
This means that the network is congested or the business is relatively slow. Then the distribution of business tasks handled by the thread pool is relatively even.

2.2.2.newSingleThreadExector

Exectors.newSingleThreadExector()–>Execution of one task, one pool, one thread

public?static?void?main(String[]?args)?{
	//一池一個(gè)工作線程,類似一個(gè)銀行有1個(gè)受理窗口
	ExecutorService?threadPool=Executors.newSingleThreadExecutor();?	
	try?{
		//模擬有10個(gè)顧客過來銀行辦理業(yè)務(wù)
		for(int?i=1;i{
				System.out.println(Thread.currentThread().getName()+"\t?辦理業(yè)務(wù)");
			});
		}
	}?catch?(Exception?e)?{
		//?TODO:?handle?exception
	}finally{
		threadPool.shutdown();
	}	}

Java explains ThreadPool thread pool

2.2.3.newCachedThreadPool

Exectors.newCachedThreadPool()–>Perform many short-term asynchronous tasks. The thread pool creates new threads as needed, but in the previously constructed threads They will be reused when available. It can be expanded, and it will be strong when it is strong. A pool of n threads, expandable, scalable, cache cache means
So how much should the number of pools be set? If the bank has only one window, then when too many people come, it will be too busy. If a bank has many windows but few people come, it will seem like a waste of resources. So how to make reasonable arrangements? This requires the use of the newCachedThreadPool() method, which is expandable and scalable

public?static?void?main(String[]?args)?{
		//一池一個(gè)工作線程,類似一個(gè)銀行有n個(gè)受理窗口
		ExecutorService?threadPool=Executors.newCachedThreadPool();?	
		try?{
			//模擬有10個(gè)顧客過來銀行辦理業(yè)務(wù)
			for(int?i=1;i{
					System.out.println(Thread.currentThread().getName()+"\t?辦理業(yè)務(wù)");
				});
			}
		}?catch?(Exception?e)?{
			//?TODO:?handle?exception
		}finally{
			threadPool.shutdown();
		}	
	}

Java explains ThreadPool thread pool

public?static?void?main(String[]?args)?{
		//一池一個(gè)工作線程,類似一個(gè)銀行有n個(gè)受理窗口
		ExecutorService?threadPool=Executors.newCachedThreadPool();?	
		try?{
			//模擬有10個(gè)顧客過來銀行辦理業(yè)務(wù)
			for(int?i=1;i{
					System.out.println(Thread.currentThread().getName()+"\t?辦理業(yè)務(wù)");
				});
			}
		}?catch?(Exception?e)?{
			//?TODO:?handle?exception
		}finally{
			threadPool.shutdown();
		}	
	}

Java explains ThreadPool thread pool

3. The underlying principle of ThreadPoolExecutor

newFixedThreadPool underlying source code

?public?static?ExecutorService?newFixedThreadPool(int?nThreads)?{
????????return?new?ThreadPoolExecutor(nThreads,?nThreads,
??????????????????????????????????????0L,?TimeUnit.MILLISECONDS,
??????????????????????????????????????new?LinkedBlockingQueue<runnable>());
????}</runnable>

As you can see, the underlying parameters include LinkedBlockingQueue blocking queue.

newSingleThreadExecutor underlying source code

public?static?ExecutorService?newSingleThreadExecutor()?{
????????return?new?FinalizableDelegatedExecutorService
????????????(new?ThreadPoolExecutor(1,?1,
????????????????????????????????????0L,?TimeUnit.MILLISECONDS,
????????????????????????????????????new?LinkedBlockingQueue<runnable>()));
????}</runnable>

newCachedThreadPool underlying source code

public?static?ExecutorService?newCachedThreadPool()?{
????????return?new?ThreadPoolExecutor(0,?Integer.MAX_VALUE,
??????????????????????????????????????60L,?TimeUnit.SECONDS,
??????????????????????????????????????new?SynchronousQueue<runnable>());
????}</runnable>

SynchronousQueue This blocking queue is a single version of the blocking queue, and the blocking queue has a capacity of 1.

These three methods actually all return an object, which is the object of ThreadPoolExecutor.

4. The seven important parameters of the thread pool

Constructor of ThreadPoolExecutor

public?ThreadPoolExecutor(int?corePoolSize,
??????????????????????????????int?maximumPoolSize,
??????????????????????????????long?keepAliveTime,
??????????????????????????????TimeUnit?unit,
??????????????????????????????BlockingQueue<runnable>?workQueue,
??????????????????????????????ThreadFactory?threadFactory,
??????????????????????????????RejectedExecutionHandler?handler)?{
????????if?(corePoolSize?<p>The above int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit , BlockingQueue workQueue, ThreadFactory threadFactory, <br> RejectedExecutionHandler handler is our seven thread parameters <br> The above is the construction method of the ThreadPoolExecutor class, with seven parameters: </p>
<p>1) <strong>corePoolSize: thread pool The number of resident core threads in </strong>, referred to as the number of cores. <br> For example, we can treat a thread pool as a bank branch. As long as the bank opens its doors, there must be at least one person on duty. This is called the number of resident core threads. For example, if a bank has all five branches open from Monday to Friday, then the number of resident core threads from Monday to Friday is 5. If business is not that frequent today and the window is 1, then the number of resident core threads today is 1 </p>
<p>2) <strong>maxImumPoolSize: The maximum number of threads that can be executed simultaneously in the thread pool. This value must be greater than or equal to 1</strong></p>
<p>3) <strong>keepAliveTime: excess idle time The survival time of threads. When the number of threads in the current pool exceeds corePoolSize, when the idle time reaches keepAliveTime, the excess threads will be destroyed until corePoolSize is left. </strong><br> If there are resident threads in the thread pool, and there is a maximum The number of threads means that it is usually resident. If the work is tense, it will be expanded to the maximum number of threads. If the business drops, we set the survival time of the excess idle threads, such as setting it to 30s. If there is no excess for 30s, When you request it, some banks close the window, so it not only expands but also shrinks. </p>
<p>4) <strong>unit: unit of keepAliveTime</strong><br> Unit: seconds, milliseconds, microseconds. </p>
<p><strong>5) workQueue: task queue, tasks that have been submitted but have not been executed </strong><br> This is a blocking queue, such as a bank, which only has 3 acceptance windows, and 4 are coming. customers. This blocking queue is the waiting area of ??the bank. Once a customer comes, he cannot be allowed to leave. The number of windows controls the number of concurrent threads. </p>
<p>6) <strong>threadFactory: Represents the thread factory that generates working threads in the thread pool. It is used to create threads. Generally, the default is </strong><br>. Threads are all created uniformly. There are new threads in the thread pool, which are produced by the thread pool factory. </p>
<p><strong>7) handler: rejection strategy, indicating how to reject the runnable request execution strategy when the current queue is full and the working thread is greater than or equal to the maximum number of threads in the thread pool (maximumPoolSize)</strong></p>
<p>For example, today is the peak customer flow at the bank. All three windows are full and the waiting area is also full. We did not choose to continue recruiting people because it was not safe, so we chose to politely refuse. </p>
<p>In the next section we will introduce the underlying working principle of the thread pool</p>
<blockquote><p><strong>Related learning recommendations: </strong><a href="http://www.miracleart.cn/java/base/" target="_blank"><strong>java basics</strong></a> </p></blockquote></runnable>

The above is the detailed content of Java explains ThreadPool thread pool. 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Tips for Writing PHP Comments Tips for Writing PHP Comments Jul 18, 2025 am 04:51 AM

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

Writing Effective PHP Comments Writing Effective PHP Comments Jul 18, 2025 am 04:44 AM

Comments cannot be careless because they want to explain the reasons for the existence of the code rather than the functions, such as compatibility with old interfaces or third-party restrictions, otherwise people who read the code can only rely on guessing. The areas that must be commented include complex conditional judgments, special error handling logic, and temporary bypass restrictions. A more practical way to write comments is to select single-line comments or block comments based on the scene. Use document block comments to explain parameters and return values at the beginning of functions, classes, and files, and keep comments updated. For complex logic, you can add a line to the previous one to summarize the overall intention. At the same time, do not use comments to seal code, but use version control tools.

Improving Readability with Comments Improving Readability with Comments Jul 18, 2025 am 04:46 AM

The key to writing good comments is to explain "why" rather than just "what was done" to improve the readability of the code. 1. Comments should explain logical reasons, such as considerations behind value selection or processing; 2. Use paragraph annotations for complex logic to summarize the overall idea of functions or algorithms; 3. Regularly maintain comments to ensure consistency with the code, avoid misleading, and delete outdated content if necessary; 4. Synchronously check comments when reviewing the code, and record public logic through documents to reduce the burden of code comments.

Effective PHP Commenting Effective PHP Commenting Jul 18, 2025 am 04:33 AM

The key to writing PHP comments is clear, useful and concise. 1. Comments should explain the intention behind the code rather than just describing the code itself, such as explaining the logical purpose of complex conditional judgments; 2. Add comments to key scenarios such as magic values, old code compatibility, API interfaces, etc. to improve readability; 3. Avoid duplicate code content, keep it concise and specific, and use standard formats such as PHPDoc; 4. Comments should be updated synchronously with the code to ensure accuracy. Good comments should be thought from the perspective of others, reduce the cost of understanding, and become a code understanding navigation device.

PHP Development Environment Setup PHP Development Environment Setup Jul 18, 2025 am 04:55 AM

The first step is to select the integrated environment package XAMPP or MAMP to build a local server; the second step is to select the appropriate PHP version according to the project needs and configure multiple version switching; the third step is to select VSCode or PhpStorm as the editor and debug with Xdebug; in addition, you need to install Composer, PHP_CodeSniffer, PHPUnit and other tools to assist in development.

Exploring Basic PHP Syntax Exploring Basic PHP Syntax Jul 17, 2025 am 04:11 AM

The basic PHP syntax includes: 1. Use wrapping code; 2. Use echo or print to output content, where echo supports multiple parameters; 3. Variables do not need to declare types, start with $. Common types include strings, integers, floating-point numbers, booleans, arrays and objects. Mastering these key points can help you get started with PHP development quickly.

Understanding PHP Variable Types Understanding PHP Variable Types Jul 17, 2025 am 04:12 AM

PHP has 8 variable types, commonly used include Integer, Float, String, Boolean, Array, Object, NULL and Resource. To view variable types, use the gettype() or is_type() series functions. PHP will automatically convert types, but it is recommended to use === to strictly compare the key logic. Manual conversion can be used for syntax such as (int), (string), etc., but be careful that information may be lost.

Understanding PHP Variables Understanding PHP Variables Jul 17, 2025 am 04:11 AM

PHP variables start with $, and the naming must follow rules, such as they cannot start with numbers and are case sensitive; the scope of the variable is divided into local, global and hyperglobal; global variables can be accessed using global, but it is recommended to pass them with parameters; mutable variables and reference assignments should be used with caution. Variables are the basis for storing data, and correctly mastering their rules and mechanisms is crucial to development.

See all articles