Threadpoolexecutor Knowledge Point Detailed

Source: Internet
Author: User

Paste the basic implementation code first:

Import Java.util.concurrent.LinkedBlockingQueue;
Import Java.util.concurrent.ThreadPoolExecutor;
Import Java.util.concurrent.ThreadPoolExecutor.AbortPolicy;
Import Java.util.concurrent.TimeUnit;

public class Threadpoolexecutortest {

/**
* @param args
*/
public static void Main (string[] args) {

Threadpoolexecutor executor = new Threadpoolexecutor (2, 5, 100,timeunit.minutes, New Linkedblockingqueue (Ten), new AbortPolicy ());
for (int i=0;i<15;i++) {
MyTask MyTask = new MyTask (i);
Executor.execute (MyTask);
SYSTEM.OUT.PRINTLN ("Thread pool Threads:" +executor.getpoolsize () + ", Number of tasks waiting to be executed in the queue:" +
Executor.getqueue (). Size () + ", number of playing other tasks performed:" +executor.getcompletedtaskcount ());
}
Executor.shutdown ();
}
}

Class MyTask implements Runnable {
private int tasknum;

public mytask (int num) {
This.tasknum = num;
}

@Override
public void Run () {
SYSTEM.OUT.PRINTLN ("Executing task" + tasknum);
try {
Thread.CurrentThread (). Sleep (40);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
SYSTEM.OUT.PRINTLN ("task" + Tasknum + "execution complete");
}
}

Threadpoolexecutor is a thread pool execution class, and based on Threadpoolexecutor it is easy to put a runnable interface task into the thread pool

Learning Threadpoolexceutor mainly learn three extension classes and four constructors:

1. Constructor:

This is the first three of the constructor of Threadpoolexceutor is based on the fourth implementation (you can view the relevant source code) now to dissect the constructor parameter meaning:

Parameter interpretation
Corepoolsize: The number of core threads that will survive, even if there are no tasks, the thread pool will maintain the minimum number of threads
Maximumpoolsize: Thread pool maintains the maximum number of threads
KeepAliveTime: The thread pool maintains the idle time allowed by the thread, and when the thread is idle for keepalivetime, it exits until the number of threads equals Corepoolsize. If Allowcorethreadtimeout is set to True, all threads exit until the number of threads is 0.
Unit: The thread pool maintains the units of idle time allowed by threads, with optional parameter values: Several static properties in Timeunit: nanoseconds, microseconds, MILLISECONDS, SECONDS.
WorkQueue: The buffer queue used by the thread pool, commonly used: Java.util.concurrent.ArrayBlockingQueue, Linkedblockingqueue, Synchronousqueue The difference can be seen in the blogger's previous article

Arrayblockingqueue has boundaries but if the number of threads >maximumpoolsize+workqueue.size () is given to handler processing

Linkedblockingqueue initialization can be infinitely large but can also be given a limit size

Synchronousqueue is a special linkedblockingqueue equivalent to the new Linkedblockingqueue (1)

There are three common strategies for queuing:

submit directly. The default option for the work queue is synchronousqueue, which will submit tasks directly to the thread without maintaining them. Here, if there is no thread available to run the task immediately, attempting to join the task to the queue will fail, and a new thread will be constructed. This policy avoids locking when processing a set of requests that may have internal dependencies. Direct submissions typically require unbounded maximumpoolsizes to avoid rejecting newly submitted tasks. This policy allows the possibility of an increase in the number of lines that are allowed to continue when the command arrives in a row that exceeds the average that the queue can handle.

unbounded queues. using unbounded queues (for example, linkedblockingqueue that do not have a predefined capacity) will cause all corepoolsize threads to be busy while the newer tasks are waiting in the queue. This way, the created thread will not exceed corepoolsize. (therefore, the value of the maximumpoolsize is not valid.) When each task is completely independent of other tasks, that is, when task execution does not affect each other, it is appropriate to use a unbounded queue, for example, in a Web page server. This queueing can be used to handle transient burst requests, which allow the possibility of an increase in the number of lines that are allowed to occur when the command reaches an average of more than the queue can handle.

bounded queues. when using limited maximumpoolsizes, bounded queues (such as arrayblockingqueue) help prevent resource exhaustion, but may be difficult to adjust and control. The queue size and maximum pool size may need to be compromised: using large queues and small pools minimizes CPU usage, operating system resources, and context switching overhead, but can result in artificially reduced throughput. If tasks are frequently blocked (for example, if they are I/O boundaries), the system may schedule more threads than you permit. Using small queues typically requires a large pool size, high CPU utilization, but may encounter unacceptable scheduling overhead, which also reduces throughput.

Handler: The number of threads in the pool is greater than maximumpoolsize, the processing policy for rejected tasks, and the default value Threadpoolexecutor.abortpolicy () related policies Also

1, AbortPolicy: Throw the exception directly. 2. Callerrunspolicy: Only use the caller's thread to run the task. 3. Discardoldestpolicy: Discards the most recent task in the queue and executes the current task. 4, Discardpolicy: Do not handle, discard.

5, of course, can also be implemented according to the application scenario needs to implement the Rejectedexecutionhandler interface customization policy. Tasks such as logging or persistence that cannot be processed.

The thread pool performs task 1, creating threads when the number of threads is less than the number of core threads. 2. When the number of threads is greater than or equal to the number of core threads and the task queue is not full, the task is placed in the task queue. 3, when the number of threads is greater than the number of core threads, and the task queue is full if the number of threads is less than the maximum number of threads, create line Chengjo threads equals the maximum number of threads, throws an exception, rejects the task

2. Extension class: (Home in writing)

Some of the more important classes of thread pools are:

Executorservice

A true thread pool interface.

Scheduledexecutorservice

can be similar to Timer/timertask to solve problems that require repetitive execution of tasks.

Threadpoolexecutor

The default implementation of Executorservice.

Scheduledthreadpoolexecutor

Inheriting Threadpoolexecutor's Scheduledexecutorservice interface implementation, the class implementation of periodic task scheduling.

A fixed-size thread pool

Executorservice pool = Executors.newfixedthreadpool (2);

Pool.execute (t1);

is actually a:

New Threadpoolexecutor (Nthreads, nthreads,0l, Timeunit.milliseconds,new linkedblockingqueue<runnable> ())

Creates a fixed-size thread pool. Each time a task is committed, a thread is created until the thread reaches the maximum size of the threads pool. Once the maximum size of the thread pool is reached, the thread pool will be replenished with a new thread if it ends up executing an exception.

Second, single task thread pool

Executorservice pool = Executors.newsinglethreadexecutor ();

is actually a:

New Threadpoolexecutor (1, 1,0l, Timeunit.milliseconds,new linkedblockingqueue<runnable> ())

Create a Executor that uses a single worker thread to run the thread in a unbounded queue.

For both of these connection pools, the size is fixed, and when the thread (or task) of the pool to be joined exceeds the maximum size of the pool, the pool of incoming threads needs to be queued.

Three, the variable size of the thread pool

Similar to the above, just change the way the pool is created:

Executorservice pool = Executors.newcachedthreadpool ();

is actually a:

New Threadpoolexecutor (0, integer.max_value,60l, timeunit.seconds,new synchronousqueue<runnable> ());

Creates a cacheable pool of threads. If the size of the thread pool exceeds the thread that is required to process the task,

Then a partially idle (60 second non-performing) thread is reclaimed, and when the number of tasks increases, the thread pool can intelligently add new threads to handle the task. This thread pool does not limit the size of the thread pool, and the thread pool size is entirely dependent on the maximum thread size that the operating system (or JVM) can create.

This implementation is interesting. The first is the unbounded thread pool, so we can find maximumpoolsize as big big. Followed by the Blockingqueue selection on the use of synchronousqueue. May be a little strange for the blockingqueue, simply said: in the queue, each insert operation must wait for the corresponding removal of another thread.

Iv. Delayed connection pooling

Scheduledexecutorservice pool = Executors.newscheduledthreadpool (2);

Scheduler.scheduleatfixedrate (New Hourtimer (), 0, 1, timeunit.hours); Continue execution in 1 hours

Scheduler.schedulewithfixedrate (New Hourtimer (), 0, 1, timeunit.hours);

is actually a:

Super (Corepoolsize, Integer.max_value, 0, Timeunit.nanoseconds,new delayedworkqueue ());

Create a thread pool of unlimited size. This thread pool supports the need to schedule and periodically perform tasks.

Threadpoolexecutor Knowledge Point Detailed

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.