Thread pool Threadpoolexecutor usage brief (GO)

Source: Internet
Author: User

First, Introduction
The thread pool class is java.util.concurrent.ThreadPoolExecutor and is commonly constructed by:

Threadpoolexecutor (int corepoolsize, int maximumpoolsize,
Long KeepAliveTime, Timeunit unit,
BlockingqueueWorkQueue,
Rejectedexecutionhandler handler)
Corepoolsize: Thread pool maintains a minimum number of threads
Maximumpoolsize: Thread pool maintains the maximum number of threads
KeepAliveTime: The thread pool maintains the idle time allowed by threads
Unit: The thread pool maintains the units of idle time allowed by threads
WorkQueue: Buffer queue used by the thread pool
Handler: thread pool processing policy for rejected tasks

A task is added to the thread pool by the Execute (Runnable) method, the task is an object of type Runnable, and the task is executed by the run () method of the Runnable type object.

When a task is added to the thread pool by the Execute (Runnable) method:

If the number of threads in the thread pool is less than corepoolsize at this point, even if the threads in the thread pool are idle, a new thread is created to handle the task being added.
If the number in the thread pool is equal to corepoolsize, but the buffer queue Workqueue is not full, then the task is placed in the buffer queue.
If the number of threads in the thread pool is greater than corepoolsize, the buffer queue Workqueue full, and the number of thread pools is less than maximumpoolsize, a new thread is built to handle the task being added.
If the number of threads in the thread pool is greater than corepoolsize, the buffer queue is workqueue full, and the number in the thread pool equals maximumpoolsize, the task is handled by handler the policy specified.

That is, the priority of the processing task is:
Core thread corepoolsize, Task queue workqueue, maximum thread maximumpoolsize, if all three are full, use handler to handle the rejected task.

When the number of threads in the thread pool is greater than corepoolsize, if a thread is idle for more than KeepAliveTime, the thread is terminated. This allows the thread pool to dynamically adjust the number of threads in the pool.

The Unit optional parameter is a few static properties in Java.util.concurrent.TimeUnit:
nanoseconds, microseconds, MILLISECONDS, SECONDS.

Workqueue I used to be: java.util.concurrent.ArrayBlockingQueue

Handler has four options:
Threadpoolexecutor.abortpolicy ()
Throw Java.util.concurrent.RejectedExecutionException exception
Threadpoolexecutor.callerrunspolicy ()
Retry adding the current task, he will automatically repeatedly call the Execute () method
Threadpoolexecutor.discardoldestpolicy ()
Abandon the old task
Threadpoolexecutor.discardpolicy ()
Abandon the current task

Ii. Examples of general usage

 Packagedemo;Importjava.io.Serializable;ImportJava.util.concurrent.ArrayBlockingQueue;ImportJava.util.concurrent.ThreadPoolExecutor;ImportJava.util.concurrent.TimeUnit; Public classtestthreadpool2{Private Static intProducetasksleeptime = 2; Private Static intProducetaskmaxnumber = 10;  Public Static voidMain (string[] args) {//construct a thread poolThreadpoolexecutor ThreadPool =NewThreadpoolexecutor (2, 4, 3, Timeunit.seconds,NewArrayblockingqueue<runnable> (3),                NewThreadpoolexecutor.discardoldestpolicy ());  for(inti = 1; I <= Producetaskmaxnumber; i++)        {            Try            {                //generate a task and add it to the thread poolString task = "[Email protected]" +i; System.out.println ("Put" +task); Threadpool.execute (NewThreadpooltask (Task)); //easy to observe, wait for some timeThread.Sleep (producetasksleeptime); }            Catch(Exception e) {e.printstacktrace (); }        }    }}/*** Tasks performed by the thread pool*/classThreadpooltaskImplementsRunnable, serializable{Private Static Final LongSerialversionuid = 0; Private Static intConsumetasksleeptime = 2000; //the data required to save the task    PrivateObject Threadpooltaskdata; Threadpooltask (Object tasks) { This. Threadpooltaskdata =tasks; }     Public voidrun () {//handle a task, the way it's handled is too simple, just a print statementSystem.out.println (Thread.CurrentThread (). GetName ()); System.out.println ("Start:" +threadpooltaskdata); Try        {            // //easy to observe, wait for some timeThread.Sleep (consumetasksleeptime); }        Catch(Exception e) {e.printstacktrace (); } threadpooltaskdata=NULL; }     PublicObject Gettask () {return  This. Threadpooltaskdata; }}

Description
1, in this program, a task is a runnable type of object, that is, a threadpooltask type of object.
2, in general, the task in addition to processing methods, but also to deal with the data, the processing of data through the construction method to the task.
3, in this procedure, the main () method is equivalent to a cruel leader, he sent a lot of tasks, and dropped to a hard-working team called ThreadPool to do.
There are at least two players in this group, and if they are not busy, the task is placed on the task list.
If the backlog of tasks is too large to fit into the task list (more than 3), hire new players to help. But based on cost considerations, you can't hire too many players and you can only hire 4.
If four players are busy, and there is a new task, the team will not be able to deal with the task will be handled by a strategy, our processing method is to continue to distribute, until the task (more brutal!). hehe).
Because the team work is cost-free, if the work is very busy, idle to 3SECONDS there is no new task, then some players will be fired, but, in order to normal operation of the group, even if the work is idle, the team members can not be less than two.
4, by adjusting the size of the producetasksleeptime and consumetasksleeptime to achieve the distribution of tasks and the speed of processing tasks to control, change these two values can be observed at different rates of the work of the program.
5, by adjusting the data referred to in 4, coupled with the adjustment of the task discard strategy, in exchange for the other three strategies, you can see different strategies under different processing methods.
6, for other uses, see the help of the JDK, it is easy to understand and use.


Another example:

 Packagedemo;ImportJava.util.Queue;ImportJava.util.concurrent.ArrayBlockingQueue;ImportJava.util.concurrent.ThreadPoolExecutor;ImportJava.util.concurrent.TimeUnit; Public classthreadpoolexecutortest{Private Static intQueuedeep = 4;  Public voidCreatethreadpool () {/** Create thread pool, minimum number of threads is 2, maximum number of threads is 4, thread pool maintenance threads idle time is 3 seconds, * Use bounded queue with queue depth of 4, if the execution program has not been closed, the task in the head of work queue will be deleted, then          Retry the execution of the program (repeat this process if it fails again), which controls the load of the task based on the queue depth. */Threadpoolexecutor TPE=NewThreadpoolexecutor (2, 4, 3, Timeunit.seconds,NewArrayblockingqueue<runnable>(queuedeep),NewThreadpoolexecutor.discardoldestpolicy ()); //Add 10 tasks to a thread pool         for(inti = 0; I < 10; i++)        {            Try{Thread.Sleep (1); }            Catch(interruptedexception e) {e.printstacktrace (); }             while(Getqueuesize (Tpe.getqueue ()) >=queuedeep) {System.out.println ("Queue is full, wait 3 seconds to add task"); Try{Thread.Sleep (3000); }                Catch(interruptedexception e) {e.printstacktrace (); }} Taskthreadpool TTP=NewTaskthreadpool (i); System.out.println ("Put I:" +i);        Tpe.execute (TTP);    } tpe.shutdown (); }    Private synchronized intgetqueuesize (Queue queue) {returnqueue.size (); }     Public Static voidMain (string[] args) {threadpoolexecutortest test=Newthreadpoolexecutortest ();    Test.createthreadpool (); }    classTaskthreadpoolImplementsRunnable {Private intindex;  PublicTaskthreadpool (intindex) {             This. index =index; }         Public voidrun () {System.out.println (Thread.CurrentThread ()+ "Index:" +index); Try{Thread.Sleep (3000); }            Catch(interruptedexception e) {e.printstacktrace (); }        }    }}

Http://blog.chinaunix.net/uid-20577907-id-3519578.html

Thread pool Threadpoolexecutor usage brief (GO)

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.