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

Home Java JavaBase Detailed explanation of java thread pool

Detailed explanation of java thread pool

Nov 26, 2019 pm 03:05 PM
java Thread Pool

Detailed explanation of java thread pool

Thread pool overview

1. The thread pool is a pool that manages threads, which can reduce the creation and destruction of threads. The resource consumption caused

Because a thread is actually an object. To create an object, you need to go through the class loading process, to destroy an object, and to go through the GC garbage collection process, all of which require resource overhead.

2. Improve the response speed. When the task arrives, compared with taking the thread from the thread pool, creating the thread yourself will definitely be much slower.

3. Reuse, and put the thread back into the pool after it is used up. , achieving the effect of reuse

(Recommended video: java video tutorial)

Thread pool execution

Make a Metaphor

Core threads are compared to regular employees of the company

Non-core threads are compared to outsourced employees

Blocking queues are compared to demand pools

Submitting tasks is compared to submissions Requirements

Detailed explanation of java thread pool

Formal execution

public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize,long keepAliveTime,TimeUnit unit,
   BlockingQueue<Runnable> workQueue,
   ThreadFactory threadFactory,
   RejectedExecutionHandler handler)
corePoolSize     核心線程數(shù)
maximumPoolSize  線程池最大線程數(shù)
keepAliveTime    空閑線程存活時(shí)間
TimeUnit         線程空閑存活時(shí)間單位
workQueue        存放任務(wù)的阻塞隊(duì)列
threadFactory    線程工廠
handler          飽和策略

● When submitting a task and the number of surviving core threads in the thread pool is less than the number of threads corePoolSize, The thread pool will create a core thread to handle submitted tasks.

● If the number of core threads in the thread pool is full, that is, the number of threads is equal to corePoolSize, a newly submitted task will be put into the task queue workQueue and queued for execution.

● When the number of surviving threads in the thread pool is equal to corePoolSize, and the task queue workQueue is also full, determine whether the number of threads reaches maximumPoolSize, that is, whether the maximum number of threads is full. If not, create a non-core The thread executes the submitted task.

● If the current number of threads reaches maximumPoolSize and new tasks come, the rejection policy will be used directly.

Several saturation strategies

AbortPolicy         拋出一個(gè)異常,默認(rèn)的
DiscardPolicy       直接丟棄任務(wù)
DiscardOldestPolicy 丟棄隊(duì)列里最老的任務(wù),將當(dāng)前這個(gè)任務(wù)繼續(xù)提交給線程池
CallerRunsPolicy    交給線程池調(diào)用所在的線程進(jìn)行處理

Thread pool exception handling

Due to the occurrence of thread processing tasks during the thread pool call Exceptions may be caught by the thread pool, so the execution of the task may be unaware, so we need to consider thread pool exceptions.

Method one:

@Test
public void test1() throws Exception {
    ExecutorService executorService = Executors.newFixedThreadPool(5);
    for (int i = 0; i < 5; i++) {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("name: " + Thread.currentThread().getName());
                    Object a = null;
                    System.out.println(a.hashCode());
                } catch (Exception e) {
                    System.out.println(e);
                }
            }
        });
    }
}

Method two:

@Test
public void test2() throws Exception {
    ExecutorService executorService = Executors.newFixedThreadPool(5);
    for (int i = 0; i < 20; i++) {
        Future<?> future = executorService.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println("name: " + Thread.currentThread().getName());
                Object a = null;
                System.out.println(a.hashCode());
            }
        });
        try {
            future.get();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

Thread pool work queue

● ArrayBlockingQueue

● LinkedBlockingQueue

● SynchronousQueue

● DelayQueue

● PriorityBlockingQueue

==ArrayBlockingQueue==

● Initialize an array of a certain capacity

● Use a reentrant lock. Unfair lock is used by default. Enqueue and dequeue share the same lock. Mutual exclusion

● is a bounded design. If the capacity is full, elements cannot be added until An element was removed

● When using it, open up a continuous memory. If the initialization capacity is too large, it will easily cause a waste of resources. If it is too small, it will easily fail to add.

==LinkedBlockingQueue==

● Use linked list data structure

● Non-continuous memory space

● Use two reentrant locks to control the entry and exit of elements respectively, and use Condition to wake up and dequeue between threads Wait

● Bounded, in the default constructor the capacity is Integer.MAX_VALUE

==SynchronousQueue==

● The internal capacity is 0

● Every deletion operation has to wait for the insertion operation

● Every insertion operation has to wait for the deletion operation

● For an element, once there is an insertion thread and a removal thread, it will soon be The insertion thread is handed over to the removal thread. This container is equivalent to a channel and does not store elements

● In a multi-task queue, it is the fastest way to process tasks.

==PriorityBlockingQueue==

● Boundless design, but capacity actually depends on system resources.

● Add elements, if more than 1, enter priority sorting

==DelayQueue==

● Borderless design

● Adding (put) does not block, removing blocking

● Elements have an expiration time

● Only expired elements will be taken out

Commonly used thread pools

● newFixedThreadPool (thread pool with a fixed number of threads)

● newCachedThreadPool (thread pool that can cache threads)

● newSingleThreadExecutor (single-threaded thread pool)

● newScheduledThreadPool (thread pool for scheduled and periodic execution)

==newFixedThreadPool==

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

Features

1. The number of core threads is the same as the maximum number of threads

2. There is no so-called non- The idle time, that is, keepAliveTime is 0

3. The blocking queue is an unbounded queue LinkedBlockingQueue

Working mechanism:

Detailed explanation of java thread pool

● Submit the task

● If the number of threads is less than the core thread, create a core thread to execute the task

● If the number of threads is equal to the core thread, add the task to the LinkedBlockingQueue blocking queue

● 如果線程執(zhí)行完任務(wù),去阻塞隊(duì)列取任務(wù),繼續(xù)執(zhí)行。

==newCachedThreadPool==

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

線程池特點(diǎn)

● 核心線程數(shù)為0

● 最大線程數(shù)為Integer.MAX_VALUE

● 阻塞隊(duì)列是SynchronousQueue

● 非核心線程空閑存活時(shí)間為60秒

Detailed explanation of java thread pool

工作機(jī)制:

● 提交任務(wù)

● 因?yàn)闆](méi)有核心線程,所以任務(wù)直接加到SynchronousQueue隊(duì)列。

● 判斷是否有空閑線程,如果有,就去取出任務(wù)執(zhí)行。

● 如果沒(méi)有空閑線程,就新建一個(gè)線程執(zhí)行。

● 執(zhí)行完任務(wù)的線程,還可以存活60秒,如果在這期間,接到任務(wù),可以繼續(xù)活下去;否則,被銷毀。

使用場(chǎng)景

用于并發(fā)執(zhí)行大量短期的小任務(wù)。

使用SynchronousQueue作為工作隊(duì)列,工作隊(duì)列本身并不限制待執(zhí)行的任務(wù)的數(shù)量。但此時(shí)需要限定線程池的最大大小為一個(gè)合理的有限值,而不是Integer.MAX_VALUE,否則可能導(dǎo)致線程池中的工作者線程的數(shù)量一直增加到系統(tǒng)資源所無(wú)法承受為止。

如果應(yīng)用程序確實(shí)需要比較大的工作隊(duì)列容量,而又想避免無(wú)界工作隊(duì)列可能導(dǎo)致的問(wèn)題,不妨考慮SynchronousQueue。SynchronousQueue實(shí)現(xiàn)上并不使用緩存空間

==newSingleThreadExecutor==

線程池特點(diǎn)

● 核心線程數(shù)為1

● 最大線程數(shù)也為1

● 阻塞隊(duì)列是LinkedBlockingQueue

● keepAliveTime為0

public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
    return new FinalizableDelegatedExecutorService
        (new ThreadPoolExecutor(1, 1,
                                0L, TimeUnit.MILLISECONDS,
                                new LinkedBlockingQueue<Runnable>(),
                                threadFactory));
}

工作機(jī)制

Detailed explanation of java thread pool

● 提交任務(wù)

● 線程池是否有一條線程在,如果沒(méi)有,新建線程執(zhí)行任務(wù)

● 如果有,講任務(wù)加到阻塞隊(duì)列

● 當(dāng)前的唯一線程,從隊(duì)列取任務(wù),執(zhí)行完一個(gè),再繼續(xù)取,一個(gè)人(一條線程)夜以繼日地干活。

使用場(chǎng)景

適用于串行執(zhí)行任務(wù)的場(chǎng)景,一個(gè)任務(wù)一個(gè)任務(wù)的執(zhí)行

==newScheduledThreadPool==

線程池特點(diǎn)

public ScheduledThreadPoolExecutor(int corePoolSize) {
    super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,new DelayedWorkQueue());
}

●?最大線程數(shù)為Integer.MAX_VALUE

●?阻塞隊(duì)列是DelayedWorkQueue

●?keepAliveTime為0

●?scheduleAtFixedRate() :按某種速率周期執(zhí)行

●?scheduleWithFixedDelay():在某個(gè)延遲后執(zhí)行

工作機(jī)制

●?添加一個(gè)任務(wù)

●?線程池中的線程從 DelayQueue 中取任務(wù)

●?線程從 DelayQueue 中獲取 time 大于等于當(dāng)前時(shí)間的task

●?執(zhí)行完后修改這個(gè) task 的 time 為下次被執(zhí)行的時(shí)間

●?這個(gè) task 放回DelayQueue隊(duì)列中

scheduleWithFixedDelay

●?無(wú)論任務(wù)執(zhí)行時(shí)間長(zhǎng)短,都是當(dāng)?shù)谝粋€(gè)任務(wù)執(zhí)行完成之后,延遲指定時(shí)間再開始執(zhí)行第二個(gè)任務(wù)

scheduleAtFixedRate

●?在任務(wù)執(zhí)行時(shí)間小于間隔時(shí)間的情況下,程序以起始時(shí)間為準(zhǔn)則,每隔指定時(shí)間執(zhí)行一次,不受任務(wù)執(zhí)行時(shí)間影響

●?當(dāng)執(zhí)行任務(wù)時(shí)間大于間隔時(shí)間,此方法不會(huì)重新開啟一個(gè)新的任務(wù)進(jìn)行執(zhí)行,而是等待原有任務(wù)執(zhí)行完成,馬上開啟下一個(gè)任務(wù)進(jìn)行執(zhí)行。此時(shí),執(zhí)行間隔時(shí)間已經(jīng)被打亂

本文來(lái)自php中文網(wǎng),java教程欄目,歡迎學(xué)習(xí)!

The above is the detailed content of Detailed explanation of java 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
1502
276
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.

Understanding the Java Virtual Machine (JVM) Internals Understanding the Java Virtual Machine (JVM) Internals Aug 01, 2025 am 06:31 AM

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

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

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

How does garbage collection work in Java? How does garbage collection work in Java? Aug 02, 2025 pm 01:55 PM

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces

Understanding Network Ports and Firewalls Understanding Network Ports and Firewalls Aug 01, 2025 am 06:40 AM

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

go by example defer statement explained go by example defer statement explained Aug 02, 2025 am 06:26 AM

defer is used to perform specified operations before the function returns, such as cleaning resources; parameters are evaluated immediately when defer, and the functions are executed in the order of last-in-first-out (LIFO); 1. Multiple defers are executed in reverse order of declarations; 2. Commonly used for secure cleaning such as file closing; 3. The named return value can be modified; 4. It will be executed even if panic occurs, suitable for recovery; 5. Avoid abuse of defer in loops to prevent resource leakage; correct use can improve code security and readability.

Comparing Java Build Tools: Maven vs. Gradle Comparing Java Build Tools: Maven vs. Gradle Aug 03, 2025 pm 01:36 PM

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac

See all articles