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:
- 1th execution of the 1th task
- 3rd task 1th execution
- 1th execution of the 2nd task
- 3rd task 2nd execution
- 2nd execution of the 2nd task
- 1th task 2nd execution
- 3rd Execution of the 3rd task
- 1th task 3rd execution
- 2nd task 3rd execution
- 3rd task 4th execution
- 4th execution of the 1th task
- 4th execution of the 2nd task
- 1th Execution of the 4th task
- Execution for the 2nd time of the 4th task;
- 3rd Execution of the 4th task
- 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:
- 1th execution of the 1th mission
- 2nd execution of the 1th mission
- 3rd execution of the 1th mission
- 4th execution of the 1th mission
- 1th execution of the 2nd mission
- 2nd execution of the 2nd mission
- 3rd execution of the 2nd mission
- 4th execution of the 2nd mission
- 1th execution of the 3rd mission
- 2nd Execution of the 3rd mission
- 3rd Execution of the 3rd mission
- 4th Execution of the 3rd mission
- 1th execution of the 4th mission
- 2nd Execution of the 4th mission
- 3rd Execution of the 4th mission
- 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.
- //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:
- 1th execution of the 1th mission
- 1th execution of the 2nd mission
- 1th execution of the 3rd mission
- 2nd execution of the 2nd mission
- 2nd execution of the 1th mission
- 2nd Execution of the 3rd mission
- 3rd execution of the 2nd mission
- 3rd execution of the 1th mission
- 3rd Execution of the 3rd mission
- 4th execution of the 2nd mission
- 4th execution of the 1th mission
- 4th Execution of the 3rd mission
- 1th execution of the 4th mission
- 2nd Execution of the 4th mission
- 3rd Execution of the 4th mission
- 4th Execution of the 4th mission
--the difference from Fixedthreadpool?
Thread pool
Thread pool Executorservice in Java