Java Concurrency Programming--executor framework

Source: Internet
Author: User

Ext.: https://www.cnblogs.com/MOBIN/p/5436482.html

Summary:

Eexecutor, as a flexible and powerful asynchronous execution framework that supports a variety of different types of task execution strategies, provides a standard way to decouple the submission and execution processes of tasks, based on the producer-consumer model, where the thread that submits the task equals the producer, the thread that executes the task equals the consumer, Using runnable to represent tasks, the executor implementation also provides support for the lifecycle, as well as mechanisms such as statistical information collection, application management mechanisms, and performance monitoring. 1.Exexctor Introduction UML diagram for executor: (several common interfaces and subclasses)
Executor:An interface that defines a method executor that receives a Runnable object, whose method signature is executor (Runnable command), Executorservice:is a more extensive subclass interface than executor, which provides a method for lifecycle management and a way to track the execution of one or more asynchronous tasks back to the future Abstractexecutorservice:Default implementation of the Executorservice execution method Scheduledexecutorservice: An interface for scheduling tasks on a timed basis scheduledthreadpoolexecutor:scheduledexecutorservice implementation, a thread pool that can schedule tasks on a scheduled basis Threadpoolexecutor:Thread pool, you can create a thread pool and return a Executorservice object by calling executors the following static factory method: description of each parameter of the 2.ThreadPoolExecutor constructorThreadpoolexecutor method Signature:
Public threadpoolexecutor (int corepoolsize,                          int maximumpoolsize,                          long KeepAliveTime,                          timeunit Unit,                          blockingqueue<runnable> WorkQueue,                          Threadfactory threadfactory,                          Rejectedexecutionhandler handler)//The latter two parameters are optional
parameter Description: corepoolsize:The number of core threads, if the thread running is less than corepoolsize, creates a new thread to perform the new task, even if the other threads in the thread pool are idle maximumpoolsize:The maximum number of threads, which allows the number of threads to be created, the corepoolsize and maximumpoolsize set boundaries to automatically adjust the pool size: Corepoolsize < number of threads running < maximumpoolsize:Create a new thread only when the queue is full corepoolsize= Number of threads running = maximumpoolsize:Create a fixed-size thread pool KeepAliveTime:If the number of threads is greater than corepoolsize, these extra threads will be terminated when their idle time exceeds KeepAliveTime Unit:KeepAliveTime the time unit of the parameter   WorkQueue:The blocking queue that holds the task, related to the size of the thread pool: when there are fewer threads running than corepoolsize, a new thread is created directly to perform the task without having to go into the queue when the number of threads running is equal to or more than corepoolsize, and when a new task is added, it is selected to join the queue. Do not create a thread directly when the queue is full, a new thread is created when a new task is available threadfactory:Create a new thread using Threadfactory, and use defaultthreadfactory to create a thread by default Handle:Define policies that handle rejected tasks, default to Threadpoolexecutor.abortpolicy, and throw when a task is rejected Rejectexecutorexception 3.Executors:Provides a series of static factory methods for creating a variety of thread pools Newfixedthreadpool: Create a thread pool that can be reused and fixed threads, and if all threads in the thread pools are active, then commit the task to wait in the queue until there are available threads ; If a thread in the thread pool ends up with an exception, a new thread will be replenished by the wire pool. Method Signature:
public static Executorservice newfixedthreadpool (int nthreads) {    return new Threadpoolexecutor (Nthreads, Nthreads,                                  0L, Timeunit.milliseconds,                                  //Use a FIFO-sort-based blocking queue, where all corepoolsize threads are busy the new task will wait in the queue                                  Linkedblockingqueue<runnable> ());}
Newsinglethreadexecutor: Creates a single-threaded executor that, if the thread ends because of an exception, a new thread continues to perform subsequent task method signatures:
public static Executorservice Newsinglethreadexecutor () {   return new Finalizabledelegatedexecutorservice                     // Corepoolsize and maximumpoolsize are equal, indicating that the fixed thread pool size is 1                        (new Threadpoolexecutor (1, 1,                                                0L, Timeunit.milliseconds,                                                New Linkedblockingqueue<runnable> ()));}
Newscheduledthreadpool: Create a thread pool method signature that can be deferred or executed periodically: Example 1: (using Newscheduledthreadpool to simulate the heartbeat mechanism)
1 public class HeartBeat {2 public     static void Main (string[] args) {3         scheduledexecutorservice executor = execut Ors.newscheduledthreadpool (5); 4         Runnable task = new Runnable () {5 public             void Run () {6                 System.out.println ("HeartBeat ........................."); 7             } 8         }; 9         executor.scheduleatfixedrate (task,5,3, timeunit.seconds);   5 seconds after the first execution, and then every 3 seconds after the execution of the ten     }11}
Output:
HeartBeat .....///5 seconds after the first output HeartBeat ...///////////////////////////////3
Newcachedthreadpool: Creates a cacheable thread pool that will be removed if the thread in the thread pools is not in use for 60 seconds, and when a new task is performed, the thread pool has a previously created available thread to reuse the available thread, or a new thread method signature is created:
public static Executorservice Newcachedthreadpool () {    return new Threadpoolexecutor (0, Integer.max_value,                                  60L , Timeunit.seconds,                                  //Use the synchronization queue, and submit the task directly to the thread                                  new synchronousqueue<runnable> ());}
Example 2:
1234567891011121314 publicclassThreadPoolTest {    publicstaticvoidmain(String[] args) throwsInterruptedException {     ExecutorService threadPool = Executors.newCachedThreadPool();//线程池里面的线程数会动态变化,并可在线程线被移除前重用        for(inti = 1; i <= 3; i ++) {            finalinttask = i;   //10个任务            //TimeUnit.SECONDS.sleep(1);            threadPool.execute(newRunnable() {    //接受一个Runnable实例                publicvoidrun() {                        System.out.println("线程名字: "+ Thread.currentThread().getName() +  "  任务名为: "+task);                }            });        }    }}
Output: (Create a new thread for each task, creating a total of 3 threads)
Thread Name: Pool-1-thread-1 The Task name is: 1 Thread Name: Pool-1-thread-2 Task Name: 2 Thread Name: pool-1-thread-3 The Task name is: 3
Uncomment the 6th line with the following output: (Always reuse a thread because Newcachedthreadpool can reuse available threads)
Thread Name: Pool-1-thread-1 The Task name is: 1 Thread Name: Pool-1-thread-1 Task Name: 2 Thread Name: Pool-1-thread-1 The Task name is: 3
Various tuning management monitoring logging and error reporting waits can be easily implemented by using executor.   life cycle of 4.ExecutorExecutorservice provides a way to manage the eecutor life cycle, and the life cycle of Executorservice includes the following: Running off and terminating three states. Executorservice is running when initialization is created. The shutdown method waits for the submitted task to complete and no longer accepts new tasks, and closing the Shutdownnow method after completing all committed tasks forces the terminating of all running tasks and no longer allows the submission of new tasks A runnable (example 2) or callable (example 3) can be submitted to Executorservice's Submit method for execution, and a futire is used to obtain the execution result of the task or to cancel task Example 3: (after the task executes and returns the execution result)
1234567891011 publicclassCallableAndFuture {    publicstatic voidmain(String[] args) throwsExecutionException, InterruptedException {        ExecutorService executor = Executors.newSingleThreadExecutor();        Future<String> future = executor.submit(newCallable<String>() {   //接受一上callable实例            publicString call() throwsException {                return"MOBIN";            }        });        System.out.println("任务的执行结果:"+future.get());    }}
Output:
Execution result of the task: Mobin
Executorcompletionservice:Implements the Completionservice, puts the completed task into the blocking queue, obtains the execution result by the take or the poll Method Example 4: (Start 10 threads, who will return the first to complete)
12345678910111213141516 publicclassCompletionServiceTest {    publicstaticvoidmain(String[] args) throwsInterruptedException, ExecutionException {        ExecutorService executor = Executors.newFixedThreadPool(10);        //创建含10.条线程的线程池        CompletionService completionService = newExecutorCompletionService(executor);        for(inti =1; i <=10; i ++) {            finalintresult = i;            completionService.submit(newCallable() {                publicObject call() throwsException {                    Thread.sleep(newRandom().nextInt(5000));   //让当前线程随机休眠一段时间                    returnresult;                }            });        }        System.out.println(completionService.take().get());   //获取执行结果    }}
The output may be different each time (between 1 and 10)
3
Designing applications through executor simplifies the development process, improves development efficiency, and facilitates concurrency, and in development if you need to create threads, you can prioritize the use of executor

Java Concurrency Programming--executor framework

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.