亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

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://ipnx.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)

Hot Topics

PHP Tutorial
1488
72
VSCode settings.json location VSCode settings.json location Aug 01, 2025 am 06:12 AM

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

python itertools combinations example python itertools combinations example Jul 31, 2025 am 09:53 AM

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

Mastering Dependency Injection in Java with Spring and Guice Mastering Dependency Injection in Java with Spring and Guice Aug 01, 2025 am 05:53 AM

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

python pytest fixture example python pytest fixture example Jul 31, 2025 am 09:35 AM

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

Troubleshooting Common Java `OutOfMemoryError` Scenarios Troubleshooting Common Java `OutOfMemoryError` Scenarios Jul 31, 2025 am 09:07 AM

java.lang.OutOfMemoryError: Javaheapspace indicates insufficient heap memory, and needs to check the processing of large objects, memory leaks and heap settings, and locate and optimize the code through the heap dump analysis tool; 2. Metaspace errors are common in dynamic class generation or hot deployment due to excessive class metadata, and MaxMetaspaceSize should be restricted and class loading should be optimized; 3. Unabletocreatenewnativethread due to exhausting system thread resources, it is necessary to check the number of threads, use thread pools, and adjust the stack size; 4. GCoverheadlimitexceeded means that GC is frequent but has less recycling, and GC logs should be analyzed and optimized.

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Advanced Spring Data JPA for Java Developers Advanced Spring Data JPA for Java Developers Jul 31, 2025 am 07:54 AM

The core of mastering Advanced SpringDataJPA is to select the appropriate data access method based on the scenario and ensure performance and maintainability. 1. In custom query, @Query supports JPQL and native SQL, which is suitable for complex association and aggregation operations. It is recommended to use DTO or interface projection to perform type-safe mapping to avoid maintenance problems caused by using Object[]. 2. The paging operation needs to be implemented in combination with Pageable, but beware of N 1 query problems. You can preload the associated data through JOINFETCH or use projection to reduce entity loading, thereby improving performance. 3. For multi-condition dynamic queries, JpaSpecifica should be used

See all articles