Examples of threading Framework executor usage

Source: Internet
Author: User

An example of the use of the JAVA5 threading Framework Executor executor is a multi-tasking execution framework (Doug Lea) under Java5, which creates a thread pool similar to the database connection pool to perform tasks. This framework consists mainly of three interfaces and their corresponding specific classes. Executor, Executorservice and Scheduledexecutorservice. 1, Executor interface: is used to perform Runnable tasks; It defines only one method-execute (Runnable command); Performs a task of type ruannable. 2. Executorservice interface: Inherits the Executor interface, which provides services to perform callable tasks and abort task execution. 3, Scheduledexecutorservice interface: Inherit the Executorservice interface, provide the service that executes the task according to the schedule. 4, Executors class: For the convenience of use, it is recommended to use Executors tool class to get Executor interface specific objects.  The executors class has several important methods, which are concise here: 1, callable (Runnable Task): Convert Runnable task to callable Task 2, Newsinglethreadexecutor (): Produce a The Executorservice object, which has only one thread available to perform the task, and if more than one task is performed, the task is executed sequentially. 3, Newcachedthreadpool (): Produces a Executorservice object with a thread pool, the size of the thread pool is adjusted as needed, and the thread returns to the thread pool for the next task when it finishes executing the task. 4, Newfixedthreadpool (int poolsize): Produces a Executorservice object with a thread pool of size poolsize, and if the number of tasks is greater than poolsize, the task is placed in a queue Sequential execution. 5. Newsinglethreadscheduledexecutor (): Produces a Scheduledexecutorservice object with a thread pool size of 1, and if there are more than one task, the task will be executed sequentially. 6, Newscheduledthreadpool (int PoolsiZe): Produces a Scheduledexecutorservice object with a thread pool size of poolsize, and if the number of tasks is greater than poolsize, the task waits for execution in a queue. For a description of the other classes of the executor framework, refer to the API documentation for Java 5 Below are a few simple examples of the use of several of the main methods in the example executors. 1, Task.java Task 2, Singlethreadexecutortest.java single-Threaded execution program test 3, Cachedthreadpooltest.java thread pool threads executing program Test 4, Fixedthreadpooltest.java thread pool threads executing program test (fixed number of threads) 5, Daemonthreadfactory.java daemon thread generation factory 6, Maxprioritythreadfactory.java Large priority thread Generation factory 7, Minprioritythreadfactory.java small priority thread Generation factory 8, Threadfactoryexecutortest.java test under Custom thread-generation factory ============= = = 1, Task.java package Executor;  Executable task public class task implements Runnable{//Interrupt signal volatile Boolean stop = false;//The number of times the task was executed private int runcount = 0;//task ID private int taskId; public task ( int taskId) {this.taskid = TaskId; System.out.println ("Create task-" + taskId); }//Perform task public void run (){while (!stop) {try {thread.sleep (ten);}catch (interruptedexception e){System.out.println ("Task interrupted ...");}//After the thread runs 3 times, the interrupt signal is set to True if (++runcount = = 3) stop = true;//Output some statements System.out.println ("" + Thread.CurrentThread (). toSt Ring () + "TTTT Execute task-" + taskId + "' s" + runcount + "th run.");}} =============== 1 End =============== 2, Singlethreadexecutortest.java package Executor; Import Java.util.concurrent.ExecutorService; Import java.util.concurrent.Executors; public class Singlethreadexecutortest{Public static void Main (string[] args) {try {//Create a single thread executor executorservice executorservice = Executors.newsingleth Readexecutor (); for (int i =1; I <= 3; i++) {Executorservice.execute (new Task (i));}Executorservice.shutdown ();} catch (Exception e){}}} =============== 2 end =============== 3, Cachedthreadpooltest.java package Executor; Import Java.util.concurrent.ExecutorService; Import java.util.concurrent.Executors; public class Cachedthreadpooltest{Public static void Main (string[] args) {try {//Jianxin thread pool, reuse them if previously constructed thread is available executorservice Executorservice = Executo Rs.newcachedthreadpool (); for (int i =1; I <= 4; i++) {Executorservice.execute (new Task (i));}Executorservice.shutdown ();} catch (Exception e){}}} =============== 3 end =============== 4, Fixedthreadpooltest.java package Executor; Import Java.util.concurrent.ExecutorService; Import java.util.concurrent.Executors; public class Fixedthreadpooltest{Public static void Main (string[] args) {try {//create thread pool of fixed threads, run these threads in a shared unbounded queue executorservice Executorservice = Exe Cutors.newfixedthreadpool (2); for (int i =1; I <= 5; i++) {Executorservice.execute (new Task (i));}Executorservice.shutdown ();} catch (Exception e){}}} =============== 4 end =============== 5, Guangzhou Software development Training Daemonthreadfactory.java package Executor; Import Java.util.concurrent.ThreadFactory; public class Daemonthreadfactory implements Threadfactory{//Create a daemon public thread newthread (Runnable r) {Thread t = new Thread (r); T.setdaemon (true); return t;}} =============== 5 End =============== 6, Maxprioritythreadfactory.java package Executor; Import Java.util.concurrent.ThreadFactory; public class Maxprioritythreadfactory implements Threadfactory{//Create one of the highest priority threads public thread Newthread (Runnable r) {Thread t = new Thread (r);//priority is the maximum, which means that the probability of switching to this thread is lower than the others T.setprio Rity (thread.max_priority); return t; }} =============== 6 end =============== 7, Minprioritythreadfactory.java package Executor; Import Java.util.concurrent.ThreadFactory; public class Minprioritythreadfactory implements Threadfactory{//Create a least-priority thread public thread Newthread (Runnable r) {Thread t = new Thread (r),//////The least priority, meaning that the probability of switching to this thread is lower than the others T.setprio Rity (thread.min_priority); return t; }} =============== 7 End =============== 8, Threadfactoryexecutortest.java package Executor; Import Java.util.concurrent.ExecutorService; Import java.util.concurrent.Executors; public class Threadfactoryexecutortest{Public static void Main (string[] args) {try {//Create a single thread executor executorservice defaultexecutor = executors.newcachedth Readpool (); Executorservice daemonexec = executors. Newcachedthreadpool (New Daemonthreadfactory ()); Executorservice maxpriorityexecutor = executors. Newcachedthreadpool (New Maxprioritythreadfactory ()); Executorservice minpriorityexecutor = executors. Newcachedthreadpool (New Minprioritythreadfactory ()); Perform the task for (int i = 1; i < i++) {Daemonexec.execute (new task (i)) with the daemon thread;}//Perform tasks with other threads for (int j = ten; J <=; j + +){if (j = =) Maxpriorityexecutor.execute (new Task (j)), else if (j = =) Minpriorityexecutor.execute (new Task (j)); El Se defaultexecutor.execute (New Task (j)); }} catch (Exception e){}every problem per thread: it does not have any restrictions on the number of threads that have been created, unless the request rate that the client can throw is limited. Disadvantages of Unlimited thread creation: 1. Thread life cycle overhead: thread creation and shutdown are not "free". 2. Resource consumption: The active thread consumes system resources, especially memory. 3. Stability. 1 thread pool in Java, the primary abstraction for task execution is not Thread, but executor. public interface Executor{/** * Executor is just a simple interface, but he creates the foundation for a flexible and powerful framework. */void Execute (Runnable command);}This framework can be used for asynchronous task execution and supports many different types of task execution strategies. It also provides a standard method for decoupling between task submissions and task execution. In addition, support for the lifecycle and hook functions can be added, such as statistics collection, application management mechanisms, and monitors and other extensions. 1.1 Create/Close 1.newCachedThreadPool Create cacheable thread pool, more recycled, less words added, no limit n2.ewfixedthreadpool (int nthreads) Create a fixed-length thread pool, Creates a thread for each task that is submitted until the maximum. If one is terminated, a new 3.newScheduledThreadPool (int corepoolsize) thread pool is added, and timed and recurring task executions are supported. Equivalent to a timer. 4.newSingleThreadExecutor () Single threaded executor, creating only the task of working threads. If it ends unexpectedly, there will be another one to replace it. It will ensure that the task queue is executed in the order specified. 5.newSingleThreadScheduledExecutor () creates a single-threaded execution program that can schedule a command to run after a given delay or perform it on a regular basis. private static final Executor Exec=executors.newfixedthreadpool (100); ServerSocket socket=new ServerSocket (80); while (true){final Socket connection=socket.accept (); Runnable task=new Runnable () {public void run () {handlerequest (connection);} }; Exec.execute (exec); The 1.2 executorservice thread will block the end of the JVM if http://is not properly closed. The tasks in the thread pool may already be completed, may be running, and others will be waiting to be executed in the queue. When it is closed, it may be gently closed, to the abrupt turn off (unplug the power). To solve the life cycle problem, Executorservice expanded executor and added some methods for life cycle management. Public interface Executorservice extends Executor{void shutdown (); List<runnable> Shutdownnow (); Boolean IsShutDown (); Boolean isterminated (); Boolean awaittermination (long timeout, timeunit unit) throws Interruptedexception; } You can turn off Executorservice, which will cause it to reject new tasks. Provides two ways to turn off Executorservice. The shutdown () method allows previously committed tasks to be performed before terminating, while the Shutdownnow () method prevents the wait task from starting and attempts to stop the currently executing task. At the time of termination, the executor has no task to perform, no task is waiting to be executed, and the new task cannot be submitted. Unused executorservice should be closed to allow recycling of their resources. Exec.shutdown (); Executorservice thread pool Java concurrency Programming-executor Framework 1.3 delay, and recurring tasks, Newscheduledthreadpool timer problems: 1. Only a unique thread can be created to perform all the timer tasks. 2. If a timertask is time-consuming, it can lead to a problem with the timeliness accuracy of other timertask 3. If TimerTask throws an unchecked exception, the timer will produce unpredictable behavior. The timer will not be restored again. After the other task in the timer has an exception, the tasks that are given to the timer will not be executed. 1.4 Combining Delayqueue If you want to build your own scheduling service, you can also consider using Delayqueue, which has a delay time associated with each object's low-coupling, and only after the expiration, Delayqueue will let you take the action to get the element. Then when the object in it is futuretask, it can form a simple dispatch queue. 2 Runnable and future, CallBack 2.1 Runnable Executor Framework makes it easy to customize an execution strategy, but to use it, your task must also implement the Runnable interface. In many server requests, there is a situation where there is a single customer request. It can perform some simple tasks, but he cannot return a value or throw a checked exception. 2.2 Callback Many tasks can cause computational delays, including executing database queries, fetching resources from the network, and making complex calculations. These tasks callback abstractions better. It can also be executed by the executor framework executors contains a lot of static methods, can runnable and privilegedaction encapsulation for callable. 2.3 Futuretask runnable and callable describe abstract computational tasks, which are usually limited, they have a beginning, and eventually end. A executor executesTasks have 4 cycles, create, submit, start, complete. Because the execution of the task takes a long time, we also want to cancel the task. The future describes the life cycle of the task and provides methods to get the results of the task, cancel the task, and verify that the task is complete or canceled. The corresponding Isdone, iscancelled () method, it can not back, once completed, will always stop in the completion state.  Get the results with get (wait)./** * @param args * @throws interruptedexception * @throws executionexception*/Public static void Main (string[] args) throws Interruptedexception{int threadcounts = number of threads used by 19;//long sum = 0; Executorservice exec = Executors.newfixedthreadpool (threadcounts); list<callable<long>> calllist = new arraylist<callable<long>> (); Generate a large list list<integer> list = new arraylist<integer> (); for (int i = 0; I <=; i++) {list.add (i);}int len = list.size ()/threadcounts;//average split list//list number no more threads (rarely exist) if (len = = 0){threadcounts = List.size ();//Use a thread to process an element in the list len = List.size ()/threadcounts;//re-average split list}for (int i = 0; i < threadcounts; i++){final list<integer> sublist; if (i = = threadCounts-1) {sublist = List.sublist (i * len, list.size ());}Else{sublist = list.sublist (i * len, Len * (i + 1) > List.size ()? List.size ():Len * (i + 1)); }//using Anonymous inner class implementation Calllist.add (New callable<long> (){Public Long Call () throws Exception {Long subsum = 0L; for (Integer i:sublist) {Subsum + = i; }System.out.println ("Assigned to Thread:" + thread.currentthread (). GetName () + "That part of the list of integers and is: tsubsum:" + subsum); return subsum; } }); } list<future<long>> futurelist = Exec.invokeall (calllist); for (future<long> future:futurelist){sum + = Future.get ();}Exec.shutdown (); SYSTEM.OUT.PRINTLN (sum); The combination of the 2.4 and the service runnable and callable classes can be submitted through the service's Submit method and return a future, which represents the task, can get the execution result of the task or cancel it. 3 Completionservice Submit a batch task to executor, and want to get the result, then you will use the future, and then constantly call Isdone to verify whether it is complete, this is too cumbersome, there is a better way, that is to complete the service, Completionservice. The poll method does not wait and returns NULL. The Take method waits. It integrates the functions of executor and blockingqueue, and you can give callable tasks to him and then use the take-and-poll method similar to the one in the queue to get the results when the results are complete. Executorcompletionservice is its implementation class. Its implementation is also relatively simple, create a blockingqueue in the constructor, use it to save the result: private final blockingqueue<future<v>> completionqueue; The submitted task is packaged into Queuefuture:private class Queueingfuture extends futuretask<void>{queueingfuture (runnablefuture<v> Task) {super (task, null); this.task = task;}protected void done (){Completionqueue.add (Task);}private final future<v> task;} Overwrite the Done method and place the result in Blockingqueue. It is not the same as getting a bunch of futuretask on it, and then returning to the go get. It can only be taken one by one, representing a single. Futuretask get may be behind the futuretask are already good, but one is not good, then stuck in the middle. 

Examples of threading Framework executor usage

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.