Java concurrency: thread pool, saturation policy, customization, expansion, java thread

Source: Internet
Author: User

Java concurrency: thread pool, saturation policy, customization, expansion, java thread

I. Preface

When we need to use a thread, we can create a new thread and explicitly call the start () method of the thread. This is very easy to implement, but there are defects in some scenarios: if you need to execute multiple tasks at the same time (that is, the number of concurrent threads is large), frequent thread creation will reduce the system efficiency, because it takes some time to create and destroy threads.

The thread pool can reuse threads. The so-called thread reuse means that a thread is not destroyed after a task is executed, and the thread can continue to execute other tasks. The Executors class in the java. lang. concurrent package provides convenience for creating a thread pool.

 

Ii. ExecutorsSimple Example

A simple example is as follows:

Package com. soft; import java. util. concurrent. executionException; import java. util. concurrent. executorService; import java. util. concurrent. executors; public class ExecutorsDemo {public static void main (String [] args) throws InterruptedException, ExecutionException {// ExecutorService executor = Executors. newSingleThreadExecutor (); // ExecutorService executor = Executors. newCachedThreadPool (); ExecutorS Ervice executor = Executors. newFixedThreadPool (5); Thread. sleep (5*1000); // The monitoring tool can capture for (int I = 0; I <10; I ++) {final int no = I; runnable runnable = new Runnable () {public void run () {try {System. out. println ("into" + no); Thread. sleep (1000L); System. out. println ("end" + no);} catch (InterruptedException e) {e. printStackTrace () ;}}; executor.exe cute (runnable); // ExecutorService has an execute () Method. The parameter of this method is of the Runnable type. You can use the execute (Runnable) method to add a task to the thread pool. The task execution method is run () of the Runnable object () method.} // End for executor. shutdown (); System. out. println ("Thread Main End! ");}}

The running result is as follows:

into0into3Thread Main End!into4into1into2end0into5end3end1end4into8into6into7end2into9end5end7end8end6end9

Explanation: this example should be easy to understand. From the running result, there are only five threads executing at any time, because the above Code passes Executors. the newFixedThreadPool (5) statement creates a fixed-length thread pool (5 in length). After one statement ends, the other thread pool starts execution.

 

Iii. Thread Pool provided by Executors

Executors is a thread factory class or a thread pool tool class. It can call its internal static methods (such as newFixedThreadPool () to create a thread pool and set parameters, executors provides different thread pool mechanisms.

 

Iv. Briefly describe the attributes of the thread pool

 

5. ThreadPoolExecutor

As mentioned above, we can use the explicit ThreadPoolExecutor constructor to construct a specific form of thread pool. ThreadPoolExecutor is a java. util. the internal thread pool of the concurrent package provides services such as thread pool management and thread scheduling. Here we will take a look at ThreadPoolExecutor.

(1) General Usage:

ExecutorService exec = new ThreadPoolExecutor(8,                8,                 0L,                TimeUnit.MILLISECONDS,                new LinkedBlockingQueue<Runnable>(100),                new ThreadPoolExecutor.CallerRunsPolicy());

The following describes the content of this example.

(2) constructor declaration:

public ThreadPoolExecutor(int corePoolSize,                                int maximumPoolSize,                                long keepAliveTime,                                TimeUnit unit,                                BlockingQueue<Runnable> workQueue,                                ThreadFactory threadFactory,                                RejectedExecutionHandler handler) {          if (corePoolSize < 0 ||              maximumPoolSize <= 0 ||              maximumPoolSize < corePoolSize ||              keepAliveTime < 0)              throw new IllegalArgumentException();          if (workQueue == null || threadFactory == null || handler == null)              throw new NullPointerException();          this.corePoolSize = corePoolSize;          this.maximumPoolSize = maximumPoolSize;          this.workQueue = workQueue;          this.keepAliveTime = unit.toNanos(keepAliveTime);          this.threadFactory = threadFactory;          this.handler = handler;      }

(3) function parameter description:

Parameter Name Meaning
CorePoolSize Basic thread pool size (core thread pool size)
MaximumPoolSize Maximum thread pool size
KeepAliveTime Maximum Lifetime of Idle threads in the thread pool that exceed corePoolSize
Unit Time Unit of The keepAliveTime Parameter
WorkQueue Task blocking queue
ThreadFactory Factory for creating a thread
Handler When the number of submitted tasks exceeds maxmumPoolSize and workQueue, the task is handed over to RejectedExecutionHandler for processing.

 

 

 

 

 

 

 

Further explanation:

A. When A new task is submitted, if the thread pool size is smaller than corePoolSize, A new thread will be created to execute the task, even if there are Idle threads in the thread pool;

B. When a new task is submitted, if the thread pool reaches the corePoolSize, the new task will be placed in the workQueue, waiting for the thread pool to be scheduled and executed;

C. When a new task is submitted, if workQueue is full and maximumPoolSize> corePoolSize, a new thread is created to execute the task;

D. When a new task is submitted, if the total number of tasks exceeds maximumPoolSize, the newly submitted task will be processed by RejectedExecutionHandler;

E. When the number of threads in the thread pool exceeds corePoolSize, if the thread's idle time reaches keepAliveTime, the idle thread is disabled.

(4) task blocking queue selection mechanism

(5) SynchronousQueue

Note: The following is an example of SynchronousQueue. Semaphore is used in this example,

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.