Core Java Talk about Threadpoolexecutor

Source: Internet
Author: User

Talking about the thread pool of the Java 7 Executors framework, students can think of several thread pools, what are they?

A total of four, respectively, they are executors newsinglethreadpool (), Newcachedthreadpool (), Newfixedthreadpool (), Newscheduledthread (), Four static methods, of course, there is a newworkstealingthreadpool () in Java 8.

But today these are not what we are going to say today, the focus is on the threadpoolexecutor used in the inside, this is what we want to say, we open the source of Newsinglethreadpool (), the thread pool of a thread.

    /*** Creates an Executor, uses a single worker thread operating * off an unbounded queue.  (Note However if this is a single * thread terminates due to a failure during execution prior to * shutdown, a new  One'll take it place if needed to execute * subsequent tasks.) Tasks is guaranteed to execute * sequentially, and no more than one task would be active at any * given time.  Unlike the otherwise equivalent * <tt>newfixedthreadpool (1) </tt> The returned executor is * guaranteed     Not to is reconfigurable to use additional threads. *     * @returnThe newly created single-threaded Executor*/     Public StaticExecutorservice Newsinglethreadexecutor () {return NewFinalizabledelegatedexecutorservice (NewThreadpoolexecutor (1, 1,                                    0L, Timeunit.milliseconds,NewLinkedblockingqueue<runnable>())); }

The point is that there are 5 parameters, namely the number of core threads, which is the number of threads needed in the thread pool at startup, and if set allowscorethreadtimeout, then the core thread will be idle after KeepAliveTime. The second maximumpoolsize is the maximum number of threads, note that the maximum number of threads is the number of core threads, and KeepAliveTime are those other threads that have exceeded the core thread to stop within the unit time; Timeunit is the time unit Blockingqueue is a blocking queue that holds tasks that are beyond the core execution thread. Now there is a problem, if the number of tasks exceeds the number of core threads, then the redundant task is to enter the Maximumpoolsize, or into the group queue it?

    /*** Creates a new {@codeThreadpoolexecutor} with the given initial * parameters and default thread factory and rejected execution handler     . * It May is more convenient to use one of the {@linkExecutors} Factory * methods instead of this general purpose constructor. *     * @paramcorepoolsize the number of threads to keep in the pool, even * if they is idle, unless {@codeAllowcorethreadtimeout} is set *@paramMaximumpoolsize the maximum number of threads to allow in the * pool *@paramKeepAliveTime When the number of threads was greater than * the core, this is the maximum time that excess     Idle threads * 'll wait for new tasks before terminating. * @paramUnit The time unit for the {@codeKeepAliveTime} argument *@paramWorkQueue the queue to use for holding tasks before they is * executed. This queue would hold only the {@codeRunnable} * Tasks submitted by the {@codeExecute} method. * @throwsIllegalArgumentException If one of the following holds:<br> * {@codeCorepoolsize < 0}<br> * {@codeKeepAliveTime < 0}<br> * {@codemaximumpoolsize <= 0}<br> * {@codeMaximumpoolsize < corepoolsize} *@throwsNullPointerException If {@codeWorkQueue} is null*/     PublicThreadpoolexecutor (intCorepoolsize,intMaximumpoolsize,LongKeepAliveTime, timeunit unit, Blockingqueue<Runnable>workQueue) {         This(Corepoolsize, maximumpoolsize, KeepAliveTime, Unit, WorkQueue, Executors.defaultthreadfactory (), Defaulth    Andler); }

I wrote an example of a test to get a better understanding of how it works. After the thread pool is full there is a rejection strategy, so I wrote the simple one ahead of time.

 Package Com.hqs.core; Import Java.util.concurrent.RejectedExecutionHandler; Import Java.util.concurrent.ThreadPoolExecutor;  Public class Implements Rejectedexecutionhandler {    @Override    publicvoid  rejectedexecution ( Runnable R, Threadpoolexecutor executor) {        + "I am rejected!" );    }}

And then write the thread pool test class, for everyone's reading convenience, I added some comments.

 PackageCom.hqs.core;ImportJava.util.concurrent.ArrayBlockingQueue;ImportJava.util.concurrent.BlockingQueue;ImportJava.util.concurrent.CountDownLatch;Importjava.util.concurrent.ExecutionException;ImportJava.util.concurrent.ThreadPoolExecutor;ImportJava.util.concurrent.TimeUnit; Public classThreadpoolexecutortestImplementsRunnable {Private inti; PrivateCountdownlatch CDL;  PublicThreadpoolexecutortest (intI, Countdownlatch CDL) {         This. i =i;  This. CDL =CDL; }     Public voidrun () {Try{TimeUnit.SECONDS.sleep (3); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (I+ "is running");    Cdl.countdown (); } @Override PublicString toString () {return"I:" +i; }     Public Static voidMain (string[] args)throwsinterruptedexception, executionexception {blockingqueue queue=NewArrayblockingqueue<> (2); Defines a blocking queue with a length of 2 Countdownlatch CDL=NewCountdownlatch (5); Set a minus latch for descending action
Defines 2 core threads, 3 maximum threads, idle threads for 5 seconds, blocks queues, refuses to process execution classes
     New New
//threadpool.allowcorethreadtimeout (TRUE);//sets whether to stop the idle core line when blocks until those for(inti = 1; I <= 6; i++) {threadpoolexecutortest T1=Newthreadpoolexecutortest (i, CDL); Threadpool.execute (t1);//futuretask future = (futuretask) threadpool.submit (t1);//note here, because the argument to submit is runnable instead of callable, so the result is null System.out.println ("Queue content:" +queue.tostring ()); Print the contents of the queue}Try{cdl.await ();//After all threads have been executed, the main thread continues down. } Catch(interruptedexception E1) {e1.printstacktrace (); }                Try{TimeUnit.SECONDS.sleep (6); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println ("Poosize:" +threadpool.getpoolsize ());  Output poolsize threadpool.shutdown (); Note that the end of the thread pool must be shown to close }}queue content:[]queue content:[]queue content:[i:3]queue content:[i:3, I:4]queue content:[i:3, I:4]i:6 I am rejected!Queue content:[i:3, I:4]1is running2 is running5 is running3is running4Is runningpoosize:2

I briefly explain this output, the first time the thread pool is initialized to start two threads, then enter into the pool for execution, but the program has not finished, followed by 3, 4 was placed in the queue, the program found the maximum thread pool is 3, the current 2 core thread pool is executing, The maximum value has not been reached, so a thread is enabled to execute 5. When the 6 came in the discovery pool is full, the queue is full, at this time can only reject off, so will go reject exception handling.

The program is executed in the order of Rejectexecutionhandler (if the pool is full), Maximumpoolsize-corepoolsize, WorkQueue, Corepoolsize, /c3>.

There is a more important point, but also the students want to know the point, that is, execute () and submit () what is the difference between?  

1. The Execute method is void, there is no return value, and the Submit () method returns the future object. Of course, some of the exceptions thrown will be inconsistent, and this is not detailed here.

2. The Execute method is defined in the executor service, and the Submit method is defined in the Executorservice.

3. The Execute method supports only the runnable parameter, and the Submit method supports the callable parameter in addition to runnable, which means that the result of the submit execution can be returned through the Future.get () method, It also means that the results of concurrent computations can be returned (this is the root cause of the difference).

So many students will also ask, two methods are executed asynchronously, then under what circumstances with the Execute or Submmit method?

such as multi-threaded parallel execution, do not need to execute the results returned when the general use of the Execute method, if the need for multi-threading parallel computation, and all need to return the results of the time, need to Submmit method, of course, submmit generally blocking, If you want to retrieve the results at the time set, if you do not get the exception is to set the parameters through the Get () method, generally processing a large number of files at the same time, it will open more than one thread on the contents of the file processed separately and return the results of the re-statistics or summary of the time is more convenient.

  

Core Java Talk about Threadpoolexecutor

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.