Java Concurrency Programming--executor framework

Source: Internet
Author: User

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,                          // 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) {    returnnew  Threadpoolexecutor (Nthreads, nthreads,                                  0L, timeunit.milliseconds,                                  //  Using a FIFO-sort-based blocking queue, all corepoolsize threads are busy and the new task will wait in the queue for the newly                                   linkedblockingqueue<runnable> ());}

Newsinglethreadexecutor: Create a single-threaded executor that, if the thread ends with an exception, creates a new thread to continue with the subsequent tasks

Method Signature:
 Public Static Executorservice Newsinglethreadexecutor () {   returnnew  Finalizabledelegatedexecutorservice                     //corepoolsize and maximumpoolsize equals, indicating a fixed thread pool size of 1                        (new threadpoolexecutor (1, 1,                                                0L, timeunit.milliseconds,                                                  New linkedblockingqueue<runnable>()));}

Newscheduledthreadpool: Create a thread pool that can be deferred or executed periodically

Method Signature:

Example 1: (using Newscheduledthreadpool to simulate the heartbeat mechanism)

 Public classHeartBeat { Public Static voidMain (string[] args) {Scheduledexecutorservice executor= Executors.newscheduledthreadpool (5); Runnable Task=NewRunnable () { Public voidrun () {System.out.println ("The HeartBeat of the" ... ".........");        }        }; Executor.scheduleatfixedrate (Task,5,3, Timeunit.seconds);//Executes 5 seconds after the first time, then executes every 3 seconds    }}

Output:

// first output after 5 seconds // output one every 3 seconds

Newcachedthreadpool: Creates a cacheable thread pool that will be removed if the thread in the thread pools is unused for 60 seconds, and when a new task is performed, the available threads are reused when the thread pool has previously created available threads, or a new thread

Method Signature:
 Public Static Executorservice Newcachedthreadpool () {    returnnew threadpoolexecutor (0, Integer.max_value,                                  60L, timeunit.seconds,                                  // use a synchronization queue to submit the task directly to the thread                                  New Synchronousqueue<runnable>());}

Example 2

 Public classThreadpooltest { Public Static voidMain (string[] args)throwsinterruptedexception {executorservice ThreadPool= Executors.newcachedthreadpool ();//the number of threads inside the thread pool changes dynamically and can be reused before thread lines are removed         for(inti = 1; I <= 3; i + +) {            Final  inttask = i;//10 Quests//TimeUnit.SECONDS.sleep (1);Threadpool.execute (NewRunnable () {//accept a runnable instance                 Public voidrun () {System.out.println ("Thread Name:" + Thread.CurrentThread (). GetName () + "task Name:" +task);        }            }); }    }}

Output: (Create a new thread for each task, creating a total of 3 threads)

Thread Name: Pool-1-thread-1 Task Name: 1 thread name: Pool-1-thread-2 Task Name: 2 thread name: Pool-1-thread-3 Task Name: 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 Task Name: 1 thread name: Pool-1-thread-1 Task Name: 2 thread name: Pool-1-thread-1 Task Name: 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 (such as Example 2) or callable (example 3) can be submitted to Executorservice's Submit method for execution, eventually returning a future to obtain the execution result of the task or cancel task Example 3: (after the task executes and returns the execution result)
 Public classCallableandfuture { Public Static voidMain (string[] args)throwsexecutionexception, interruptedexception {executorservice executor=Executors.newsinglethreadexecutor (); Future<String> future = Executor.submit (NewCallable<string> () {//accept a callable instance             PublicString Call ()throwsException {return"Mobin";        }        }); System.out.println ("Task Execution Result:" +future.get ()); }}

Output:

Execution result of the task: Mobin

Executorcompletionservice: implements Completionservice, puts completed tasks into the blocking queue, and obtains execution results by take or poll method

Example 4: (Start 10 threads, who will return first to finish)
 Public classCompletionservicetest { Public Static voidMain (string[] args)throwsinterruptedexception, executionexception {executorservice executor= Executors.newfixedthreadpool (10);//Create a thread pool with 10. ThreadsCompletionservice Completionservice =NewExecutorcompletionservice (executor);  for(inti = 1; I <=10; i + +) {            Final  intresult =i; Completionservice.submit (Newcallable () { PublicObject Call ()throwsException {thread.sleep (NewRandom (). Nextint (5000));//leave the current thread dormant for a while                    returnresult;        }            });   } System.out.println (Completionservice.take (). get ()); //Get execution Results    }}

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.