Thread pool Executorservice in Java

Source: Internet
Author: User

Example

    ImportJava.util.concurrent.ExecutorService; Importjava.util.concurrent.Executors; ImportJava.util.concurrent.ScheduledExecutorService;  Public classCh09_executor {Private Static voidRun (Executorservice threadPool) { for(inti = 1; I < 5; i++) {                    Final intTaskID =i; Threadpool.execute (NewRunnable () {@Override Public voidrun () { for(inti = 1; I < 5; i++) {                                Try{Thread.Sleep (20);//To test the results, it takes time for each task to execute.}Catch(interruptedexception e) {e.printstacktrace (); } System.out.println ("First" + TaskID + "sub-task" + i + "Execution");                }                        }                    }); } threadpool.shutdown ();//the task is completed and the thread pool is closed       }                     Public Static voidMain (string[] args) {//Create a thread pool that can hold 3 threadsExecutorservice Fixedthreadpool = Executors.newfixedthreadpool (3); //the size of the thread pool is dynamically allocated based on the number of tasks performedExecutorservice Cachedthreadpool =Executors.newcachedthreadpool (); //creates a thread pool of a single threads, and if the current thread breaks abruptly when the task is executed, a new thread is created to replace it to continue the taskExecutorservice Singlethreadpool =Executors.newsinglethreadexecutor (); //effect similar to timer timerScheduledexecutorservice Scheduledthreadpool = Executors.newscheduledthreadpool (3);      Run (Fixedthreadpool); //run (Cachedthreadpool); //run (Singlethreadpool); //run (Scheduledthreadpool);         }            }  


Cachedthreadpool

Cachedthreadpool creates a buffer that caches the initialized thread. Terminates and removes a thread that has not been used for 60 seconds from the cache.

If the thread is available, use the previously created thread,

If the thread is not available, the new thread is created.


    • reuse: cache pool, first see if there are no previously established threads, if any, reuse; if not, build a new thread to join the pool
    • usage Scenario: A cache pool is often used to perform asynchronous tasks that are short-lived, so it is not used in some connection-oriented daemon servers.
    • timeout: The thread that can reuse, must be timeout idle in the pool threads, the default timeout is 60s, more than this idle time, the thread instance will be terminated and removed from the pool.
    • End: Note that the thread that is put into the cachedthreadpool does not have to worry about its end, exceeding timeout inactivity, which is automatically terminated.

    //the size of the thread pool is dynamically allocated based on the number of tasks performedExecutorservice Cachedthreadpool =Executors.newcachedthreadpool ();  Public StaticExecutorservice Newcachedthreadpool () {return NewThreadpoolexecutor (0,//Core Pool SizeInteger.max_value,//Maximum Pool size30),//Keep Alive timeTimeunit.seconds,NewSynchronousqueue<runnable>()); The result of the execution: the 4th task of the 1th time of the 1th task executes the 3rd time of the 1th task of the 1th time to perform the 2nd task of the 1th time to perform the 3rd task of the 2nd time to perform the 4th task of the 2nd time to perform the 2nd task 2nd       The 2nd implementation of the 1th task, the 3rd of the 2nd task, the 4th of the 3rd task, the 3rd of the 3rd task, the 1th of the 3rd task, and the 2nd execution of the 4th task. The 4th execution of the 4th task for the 4th time of the 3rd task is performed alternately in 4 tasks. Fixedthreadpool in Fixedthreadpool, there is a fixed-size pool.    If the task that needs to be performed exceeds the pool size, then the extra task is waiting until the idle thread executes the task, and if the task currently needs to be performed is less than the pool size, the idle thread will not be destroyed. Reuse: Fixedthreadpool and Cachethreadpool almost, but also can be reuse to use, but can not be built at any time a new thread fixed number: its unique is that at any point, a maximum of a fixed number of active threads exist, at this time if there are new threads to be established, You can only wait in another queue until a thread in the current thread terminates directly out of the pool timeout: Unlike Cachethreadpool, Fixedthreadpool does not have an idle mechanism (possibly, but since the document is not mentioned, it must be very long, Similar to relying on the upper layer of TCP or UDP idle mechanism, such as), the use of the scene: So Fixedthreadpool most for some very stable and fixed regular concurrent threads, more for the server source code analysis: From the source code of the method, the cache pool and the fixed pool call is the same underlying pool , except for different parameters: fixed pool thread count, and 0 seconds idle (no idle) cache pool thread support 0-Integer.max_value (apparently completely without regard to the host's resource tolerance), 60 seconds idle//Create a thread pool that can hold 3 threadsExecutorservice Fixedthreadpool = Executors.newfixedthreadpool (3);  Public StaticExecutorservice Newfixedthreadpool (intnthreads) {              return NewThreadpoolexecutor (Nthreads,//Core Pool SizeNthreads,//Maximum Pool size0L,//Keep Alive timeTimeunit.milliseconds,NewLinkedblockingqueue<runnable>()); }  

Execution Result:

    1. 1th execution of the 1th task   
    2. 3rd task 1th execution   
    3. 1th execution of the 2nd task   
    4. 3rd task 2nd execution    
    5. 2nd execution of the 2nd task   
    6. 1th task 2nd execution   
    7. 3rd Execution of the 3rd task   
    8. 1th task 3rd execution   
    9. 2nd task 3rd execution   
    10. 3rd task 4th execution   
    11. 4th execution of the 1th task   
    12. 4th execution of the 2nd task   
    13. 1th Execution of the 4th task   
    14. Execution    for the 2nd time of the 4th task;
    15. 3rd Execution of the 4th task   
    16. Execution    for the 4th time of the 4th task;


A fixed-size thread pool was created with a capacity of 3, and then 4 tasks were executed in a loop. As you can see from the output, the first 3 tasks are executed, and then the idle thread executes the 4th task .


Singlethreadexecutor

Singlethreadexecutor gets a single thread that will ensure that your task executes.

if the current thread terminates unexpectedly, a new thread will be created to proceed with the task, which is different from the thread we created directly, and Newfixedthreadpool (1).

    //creates a thread pool of a single threads, and if the current thread breaks abruptly when the task is executed, a new thread is created to replace it to continue the taskExecutorservice Singlethreadpool =Executors.newsinglethreadexecutor ();  Public StaticExecutorservice Newsinglethreadexecutor () {return NewFinalizabledelegatedexecutorservice (NewThreadpoolexecutor (1,//Core Pool Size1,//Maximum Pool size0L,//Keep Alive timeTimeunit.milliseconds,NewLinkedblockingqueue<runnable>())); }  


Execution Result:

    1. 1th execution of the 1th mission
    2. 2nd execution of the 1th mission
    3. 3rd execution of the 1th mission
    4. 4th execution of the 1th mission
    5. 1th execution of the 2nd mission
    6. 2nd execution of the 2nd mission
    7. 3rd execution of the 2nd mission
    8. 4th execution of the 2nd mission
    9. 1th execution of the 3rd mission
    10. 2nd Execution of the 3rd mission
    11. 3rd Execution of the 3rd mission
    12. 4th Execution of the 3rd mission
    13. 1th execution of the 4th mission
    14. 2nd Execution of the 4th mission
    15. 3rd Execution of the 4th mission
    16. 4th Execution of the 4th mission


4 tasks are executed sequentially
.


Scheduledthreadpool

Scheduledthreadpool is a fixed-size thread pool, similar to Fixedthreadpool , and the task is performed on a timed basis.

    1. //effect similar to timer timer   
Scheduledexecutorservice Scheduledthreadpool = Executors.newscheduledthreadpool (3);      Public Scheduledthreadpoolexecutor (int  corepoolsize) {          Super(corepoolsize,      //  Core Pool size                //maximum pool size                0,                 // Keep Alive   time               timeunit.nanoseconds,                new  delayedworkqueue ());  }  


Execution Result:

    1. 1th execution of the 1th mission
    2. 1th execution of the 2nd mission
    3. 1th execution of the 3rd mission
    4. 2nd execution of the 2nd mission
    5. 2nd execution of the 1th mission
    6. 2nd Execution of the 3rd mission
    7. 3rd execution of the 2nd mission
    8. 3rd execution of the 1th mission
    9. 3rd Execution of the 3rd mission
    10. 4th execution of the 2nd mission
    11. 4th execution of the 1th mission
    12. 4th Execution of the 3rd mission
    13. 1th execution of the 4th mission
    14. 2nd Execution of the 4th mission
    15. 3rd Execution of the 4th mission
    16. 4th Execution of the 4th mission


--the difference from Fixedthreadpool?

Thread pool

Thread pool Executorservice in Java

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.