Java Thread Cheng executors (i)

Source: Internet
Author: User

I. BACKGROUND

Threads belong to the system scarce resources, when the use of threads, if the unlimited creation of threads, high CPU load, can cause the system to run slowly, and worse, the direct outage.

On this basis, we hope that when using threads, it is possible to put the number of system threads in a manageable range and to implement thread reuse whenever possible.

Second, executors analysis

Executors Sample DEMO

  

/** * @authorBinH * @date 2018/01/24*/ PackageOrg.lsnbin.thread;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors; Public classThreadanalyze {Private    StaticExecutorservice fexecutor = Executors.newfixedthreadpool (20);  Public Static voidMain (string[] args) { for(inti = 0; I < 20; i++) {Fexecutor.execute (NewThreadanalyze ().NewTask ()); }    }        Private classTaskImplementsrunnable{@Override Public voidrun () {System.out.println ("Thread Name--" +Thread.CurrentThread (). GetName ()); }    }}

Sample Analysis:

1. Initialize a thread pool containing 10 threads using executors

2. Use the Execute method to submit 20 tasks, print the name of a thread

3. The life cycle of the thread responsible for performing the task is referred to executors management.

Three, executors internal analysis

Executors is the factory class of the thread pool, internally based on the Threadpoolexecutor implementation, encapsulating the threadpoolexecutor and providing a relative approach.

  Newfixedthreadpool

 Public Static Executorservice newfixedthreadpool (int  nthreads) {        returnnew  Threadpoolexecutor (Nthreads, nthreads,                                      0L, timeunit.milliseconds,                                      new Linkedblockingqueue<runnable>());    }

Initializes a certain number of thread pools, and when Corepoolsize=maximumpoolsize, uses Linkedblockingqueue as the blocking queue, but does not release threads when the thread pool is not in use.

Newcachedthreadpool

 Public Static Executorservice Newcachedthreadpool () {        returnnew threadpoolexecutor (0, Integer.max_value,                                      60L, timeunit.seconds,                                      new synchronousqueue<runnable> ());    }
The thread is not initialized, the thread is created when it is needed, the maximum allowable number is Integer.max_value, the synchronousqueue is used as the blocking queue, and the thread is freed when the thread is idle KeepAliveTime.
Prone to problems: in high concurrency situations, a large number of threads are created in a flash, and serious performance problems occur.

Newsinglethreadexecutor

 Public Static Executorservice Newsinglethreadexecutor () {        returnnew  Finalizabledelegatedexecutorservice            (new threadpoolexecutor (1, 1,                                    0L, Timeunit.milliseconds,                                    new linkedblockingqueue<runnable>()));    }
Initializes a thread pool with only one threads, and if the thread ends with an exception, it re-creates a new thread. Threads are not available, using Linkedblockingqueue as the blocking queue. Only one thread can guarantee the order of the tasks to be executed.

Newscheduledthreadpool

 Public Static Scheduledexecutorservice newscheduledthreadpool (int  corepoolsize) {        returnNew  Scheduledthreadpoolexecutor (corepoolsize);    }
Initializes a thread pool for a certain number of threads, and the tasks in the thread pools can periodically execute the submitted tasks within a specified amount of time. Can be used for periodic synchronization.

Newworkstealingpool--JDK1.8

 Public Static Executorservice newworkstealingpool (int  parallelism) {        returnnew  Forkjoinpool            (parallelism,             forkjoinpool.defaultforkjoinworkerthreadfactory,             null true );    }
Create a thread pool that holds enough threads to support a given level of parallelism, and reduce contention by using multiple queues, you need to specify parallelism parallel parameters, and if not specified, the default number of CPUs.

Forkjoinpool: A thread pool that supports large-task decomposition into small tasks, which is a Java8 new thread pool that is typically used with subclasses recursiveaction or recursivetask of forkjointask interfaces.

Iv. Threadpoolexecutor Analysis

  PublicThreadpoolexecutor (intCorepoolsize,intMaximumpoolsize,LongKeepAliveTime, timeunit unit, Blockingqueue<Runnable>WorkQueue, Threadfactory threadfactory, Rejectedexecutionha Ndler handler) {if(Corepoolsize < 0 | |maximumpoolsize<= 0 | |maximumpoolsize< Corepoolsize | |KeepAliveTime< 0)            Throw Newillegalargumentexception (); if(WorkQueue = =NULL|| Threadfactory = =NULL|| Handler = =NULL)            Throw NewNullPointerException ();  This. ACC = System.getsecuritymanager () = =NULL?NULL: Accesscontroller.getcontext ();  This. corepoolsize =corepoolsize;  This. maximumpoolsize =maximumpoolsize;  This. WorkQueue =WorkQueue;  This. KeepAliveTime =Unit.tonanos (KeepAliveTime);  This. Threadfactory =threadfactory;  This. Handler =handler; }

Parametric analysis:

1, Corepoolsize

The number of thread pool core threads. When the thread pool submits a task, the thread pool creates a new thread and executes the task until the number of threads running in the thread pool equals corepoolsize.

When a task commit continues, it is placed in the blocking queue. Use the Prestartcorethread () method to pre-create and start all core threads in advance.

2, Maximumpoolsize

The maximum number of threads available for the thread pool. When the number of threads equals corepoolsize, if the current blocking queue is full, a new thread is created and the task is executed when the task continues to be submitted. If the number of threads is less than maximumpoolsize.

3, KeepAliveTime

Thread pool threads idle time to live. By default, this is only useful if the condition is greater than corepoolsize.

4. Unit

KeepAliveTime the unit of survival time.

5, WorkQueue

The blocking queue that is used to hold tasks waiting to be performed. The JDK implements queues in the following ways:

Arrayblockingqueue: A bounded blocking queue based on an array structure that sorts tasks according to FIFO (first-in-one-out).

      Linkedblockingqueue: A blocking queue based on a linked list structure,According toFIFO (in-first-out) sort task. Effect ratioArrayblockingqueue good.

Delayqueue: Unbounded blocking queue with deferred execution.

Synchronousqueue: A blocking queue that cannot store any elements, each inserted operation must wait for another corresponding delete operation, or the insert will remain blocked.

The second thread must wait for the previous thread to end.

Priorityblockingqueue: Unbounded blocking queue with priority.

6, Threadfactory

Create a thread factory

Default Factory implementation:

  

defaultthreadfactory () {            = System.getsecuritymanager ();             null) ? S.getthreadgroup ():                                  Thread.CurrentThread (). Getthreadgroup ();             = "pool-" +                          +                         "-thread-";        }

7, Handler

The saturation policy of the thread pool, for cases where the number of threads is saturated and the blocking queue is full. The processing logic that is triggered when a task continues to commit. The thread pool provides 4 strategies:

AbortPolicy: Runs directly out of the exception, the default policy.

Discardpolicy: Discards the task directly, does not process.

Discardoldestpolicy: Discards the previous old task in the blocking queue and executes the new task.

Callerrunspolicy: Executes the task with the caller's thread.

  

Threadfactory

Java Thread Cheng executors (i)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.