Java Thread Pool---executorservice

Source: Internet
Author: User

1. Thread pool 1.1 when using the thread pool
    • Single task processing time is relatively short.
    • The number of tasks that will need to be handled is large.
1.2 Benefits of using the thread pool
    • Reduce the time spent on creating and destroying threads and the overhead of system resources.
    • If you do not use a thread pool, it is possible to cause the system to create a large number of threads that consume system memory and "over-switch";
2.ExecutorService and Executors2.1 Introduction

Executorservice is an interface that inherits the executor,

publicinterface ExecutorService extend Executor{}

Executor is also an interface that contains only one method:

publicinterface Executor {    void execute(Runnable command);}

The top interface of the thread pool in Java is excutor, but strictly speaking, >>exector is not a thread pool, but just a tool for executing threads, the real thread > Pool interface is executorservice.

3.Executors

It is a static factory class, it can produce different types of thread pool, part of the source code is as follows:

 Public classExecutors {//newfixedthreadpool Public StaticExecutorserviceNewfixedthreadpool(intNthreads) {return NewThreadpoolexecutor (Nthreads, Nthreads,0L, Timeunit.milliseconds,NewLinkedblockingqueue<runnable> ());}//newcachethreadpool  Public StaticExecutorserviceNewcachedthreadpool() {return NewThreadpoolexecutor (0, Integer.max_value, -L, Timeunit.seconds,NewSynchronousqueue<runnable> ()); }//newscheduledthreadpool    Public StaticScheduledexecutorserviceNewscheduledthreadpool(intCorepoolsize) {return NewScheduledthreadpoolexecutor (corepoolsize); }//newstringooo}

Let's look at a specific example and illustrate the similarities and differences between them.

 PackageThreadImportJava.util.concurrent.ExecutorService;ImportJava.util.concurrent.Executors;ImportJava.util.concurrent.ScheduledExecutorService;/** * Created by Yang on 16-7-11. * * Public  class ch09_executor {    Private Static void Run(Executorservice ThreadPool) { for(inti =1; I <5; i++) {Final intTaskid=i; Threadpool.execute (NewRunnable () {@Override                 Public void Run() { for(intI=1;i<5; i++) {Try{Thread.Sleep ( -); }Catch(Interruptedexception e)                        {E.printstacktrace (); } System.out.println ("section"+taskid+"sub-task "+i+"Secondary Execution");        }                }            });    } threadpool.shutdown (); } Public Static void Main(string[] args) {//Create a thread pool that can hold 3 threadsExecutorservice fixedthreadpool= Executors.newfixedthreadpool (3);//The size of the thread pool is dynamically allocated according to the task performedExecutorservice Cachethreadpool=executors.newcachedthreadpool ();//Creates a thread pool of individual threads, and if the current thread breaks abruptly when the task is executed, a new thread is created to replace it to continue execution.Executorservice Singlethreadpool=executors.newsinglethreadexecutor ();//effect similar to timer timerScheduledexecutorservice Scheduledthreadpool=executors.newscheduledthreadpool (3);//Run (Fixedthreadpool); (1)        //run (Cachethreadpool);//(2)       //Run (Singlethreadpool);//(3)       //Run (Scheduledthreadpool);//(4)}}
4.4 Common thread pool 4.1 cachedthreadpool

Cachedthreadpool creates a buffer, caches the initialized thread, terminates and removes the thread that has been unused for 6 seconds from the cache.
If the thread is available, use the previously created thread. If the thread is not available, create a new thread.
. Reuse:
Cache-type pool, first look at the pool there are no previously established threads, if there is, reuse, if not, create a new thread to join the pool,
Usage Scenarios:
Cache pools are typically used to perform some short-lived asynchronous tasks, so they are not used in a number of connection-oriented daemon servers.
Timeout:
The thread that can be reuse must be the middle of the pool in timeout idle, the default timeout is 60s, more than this idle time, the thread instance will be terminated and the pool removed.
End:
The thread that is put into the cachedthreadpool does not have to worry about its end, exceeding timeout inactivity, which is automatically terminated.
Example Explanation:
Remove (2) The comment, run, and get the result as follows:

第1次任务的第1次执行第3次任务的第1次执行第2次任务的第1次执行第4次任务的第1次执行第3次任务的第2次执行第1次任务的第2次执行第2次任务的第2次执行第4次任务的第2次执行第3次任务的第3次执行第1次任务的第3次执行第2次任务的第3次执行第4次任务的第3次执行第3次任务的第4次执行第2次任务的第4次执行第4次任务的第4次执行第1次任务的第4次执行

As you can see from the results, 4 tasks are performed alternately.

4.2FixedThreadPool

In Fixedthreadpool, there is a fixed-size pool,
If the task that needs to be performed exceeds the pool size, the more outgoing task waits until there is a thread that is idle to perform 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 removed directly from the pool.
Timeout:
Unlike Cachethreadpool, Fixedthreadpool has no idle mechanism
Usage Scenarios:
So Fixedthreadpool most for some very stable and fixed regular concurrent threads, more for the server
Source Analysis:
From the source 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
Example Explanation:
Remove the comment (1) and run the result as follows:

第1次任务的第1次执行第3次任务的第1次执行第2次任务的第1次执行第1次任务的第2次执行第3次任务的第2次执行第2次任务的第2次执行第1次任务的第3次执行第3次任务的第3次执行第2次任务的第3次执行第1次任务的第4次执行第3次任务的第4次执行第2次任务的第4次执行第4次任务的第1次执行第4次任务的第2次执行第4次任务的第3次执行第4次任务的第4次执行

A fixed-size thread pool is created with a capacity of 3 and then loops through 4 tasks, as shown in the output, the first 3 tasks are executed, and then the idle thread executes the 4th task.

4.3SingleThreadExecutor
    • Singlethreadexector gets a single thread that will ensure that your task executes.
    • Single thread, only one thread can be in any time pool
    • 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).
    • Use the same underlying pool as the cache pool and the fixed pool, but the number of threads is 1-1, 0 seconds idle (no idle)
      Remove the (3) comment. See execution results as follows:
第1次任务的第1次执行第1次任务的第2次执行第1次任务的第3次执行第1次任务的第4次执行第2次任务的第1次执行第2次任务的第2次执行第2次任务的第3次执行第2次任务的第4次执行第3次任务的第1次执行第3次任务的第2次执行第3次任务的第3次执行第3次任务的第4次执行第4次任务的第1次执行第4次任务的第2次执行第4次任务的第3次执行第4次任务的第4次执行

The four tasks are executed sequentially.

4.4 Scheduledthreadpool

Scheduledthreadpool is a fixed-size thread pool that, like Fixedthreadpool, performs a scheduled task.
The result of removing (4) The results is the same as the fixedthreadpool result, the main scheduledthreadpool is not here, but a timed task, see the following example:

 PackageThreadImportJava.util.concurrent.Executors;ImportJava.util.concurrent.ScheduledExecutorService;ImportJava.util.concurrent.TimeUnit;/** * Created by Yang on 16-7-11. * * Public  class myscheduledtask implements Runnable {    PrivateString Tname; Public Myscheduledtask(String name) { This. tname=name; } Public void Run() {System.out.println (tname+"Task time delay 2 seconds execution!"); } Public Static void Main(string[] args) {Scheduledexecutorservice scheduledpool= Executors.newscheduledthreadpool (2);        Scheduledexecutorservice Singschedulepool=executors.newsinglethreadscheduledexecutor (); Myscheduledtask mt1=NewMyscheduledtask ("MT1"); Myscheduledtask mt2=NewMyscheduledtask ("MT2");//Start MT1 task execution with ScheduledthreadpoolScheduledpool.schedule (MT1,2, timeunit.seconds);//Start mt2 with Singlescheduledthreadpool;Singschedulepool.schedule (MT2, -, timeunit.milliseconds);        Scheduledpool.shutdown ();    Singschedulepool.shutdown (); }}

Results:

mt1任务时延时2秒执行!mt2任务时延时2秒执行!

After the program runs for 2 seconds, the results are displayed, stating that the thread was executed after 2 seconds.

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.