Java Threads Java thread pool Executorservice

Source: Internet
Author: User

Example
import Java.util.concurrent.ExecutorService;  Import java.util.concurrent.Executors;    Import Java.util.concurrent.ScheduledExecutorService;  Public classCh09_executor {Private Static voidRun (Executorservice threadPool) { for(inti =1; I <5; i++) {FinalintTaskID =i; Threadpool.execute (NewRunnable () {@Override Public voidrun () { for(inti =1; I <5; i++) {                            Try{Thread.Sleep ( -);//To test the results, it takes time for each task to execute.}Catch(interruptedexception e) {e.printstacktrace (); } System. out. println ("Section"+ TaskID +"Sub-task"+ i +"Times 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 size                                  60L,//Keep Alive timeTimeunit.seconds,NewSynchronousqueue<runnable>()); }  

Execution Result:

The 1th time of the 1th mission, the  1th of the 4th task, the 3rd implementation of the 1th task, the 2nd times of the 1th task, the 3rd of the 2nd task, and the 4th execution of the 2nd sub-task, and the 2nd execution of the 2nd task.  The 2nd time of  The 1th mission, the  3rd  of the 2nd task, the 4th execution of the 3rd task, 3rd times of the 3rd task, and the 1th execution of the 3rd task. 4th Execution of the 3rd task for the 4th time of the 1th Mission: 4th execution of the  4th task  

4 tasks are performed alternately .

Fixedthreadpool

In Fixedthreadpool, there is a fixed-size pool.

If the task you currently need to perform exceeds the pool size, then the extra task is waiting until a thread with idle threads executes the task.

If the task currently needs to be performed is less than the pool size, the idle thread is not destroyed.

      • reuse:Fixedthreadpool and Cachethreadpool are similar, but also can reuse use, but can not build new threads at any time
      • Fixed number: What is unique is that at any point in time, there can be at most a fixed number of active threads, and if a new thread is to be established, it can only wait in another queue until a thread in the current thread terminates and is moved 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 the TCP or UDP idle mechanism that relies on the upper layer),
      • usage Scenario: so Fixedthreadpool most for some very stable and fixed regular concurrent threads, more for the server
      • Source Analysis: from the source code of the method, the cache pool and the fixed pool call the same underlying pool, except that the parameters are different:
        Fixed pool thread count, and is 0 seconds idle (no idle)
        Cache Pool Threads Support 0-integer.max_value (obviously not considering 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 size                                      0L,//Keep Alive timeTimeunit.milliseconds,NewLinkedblockingqueue<runnable>()); }  

Execution Result:

The 1th time of the 1th mission, the  1th of the 3rd task, the 2nd implementation of the 1th task, the 3rd times of the 2nd task, the 2nd of the 2nd task, and the 1th execution of the 2nd sub-task, and the 3rd execution of the 3rd task.  The 3rd time of  The 1th mission, the  3rd  of the 2nd task, the 3rd execution of the 4th task, 1th times of the 4th task, and the 2nd execution of the 4th task. 3rd Execution of the 4th task for the 2nd time of the 4th Mission: 4th execution 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 Size                                    1,//Maximum Pool size                                    0L,//Keep Alive timeTimeunit.milliseconds,NewLinkedblockingqueue<runnable>())); }  

Execution Result:

The 1th time of the 1th mission, the  2nd  of the 1th task, the 1th execution of the 3rd task, 1th times of the 4th task, and the 2nd execution of the 1th task. The 3rd time of the 2nd mission, the  4th  of the 2nd task, the 3rd execution of the 1th task, 3rd times of the 2nd task, and the 3rd execution of the 3rd task. 2nd of the 4th task for the 1th time of the 4th task the 4th Execution of the 3rd task, 4th execution of the 4th sub-task    

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.

//effect similar to timer timerScheduledexecutorservice Scheduledthreadpool = Executors.newscheduledthreadpool (3);  PublicScheduledthreadpoolexecutor (intcorepoolsize) {Super (corepoolsize,//Core Pool SizeInteger.max_value,//Maximum Pool size              0,//Keep Alive timeTimeunit.nanoseconds,Newdelayedworkqueue ()); }  

Execution Result:

The 1th time of the 1th mission, the  1th  of the 2nd task, the 3rd execution of the 1th task, 2nd times of the 2nd task, and the 1th execution of the 2nd task. The 3rd time of the 2nd mission, the  3rd  of the 1th task, the 3rd execution of the 3rd task, 2nd times of the 4th task, and the 1th execution of the 4th task. 2nd of the 4th task for the 1th time of the 4th task the 4th Execution of the 3rd task, 4th execution of the 4th sub-task    

--the difference from Fixedthreadpool?

Java Threads Java thread pool Executorservice

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.