Java Concurrency Programming Executor

Source: Internet
Author: User
Tags terminates

The Executor framework refers to a number of Executor-related functional classes in a series of concurrency libraries introduced in Java 5, including the thread pool, Executor,executors,executorservice,completionservice, Future,callable and so on. Their relationship is:

A programming method for concurrent programming is to split the task into columns of small tasks, namely runnable, and then commit to a Executor execution,executor.execute (runnalbe) . The executor uses the internal thread pool to complete the operation at execution time.

First, create a thread pool

The Executors class provides a series of factory methods for creating a first thread pool, and the returned thread pool implements the Executorservice interface.

 Public Static Executorservice newfixedthreadpool (int nthreads)

Creates a thread pool of a fixed number of threads.

 Public Static Executorservice Newcachedthreadpool ()

Creates a cacheable thread pool that calls execute to reuse previously constructed threads if the threads are available. If an existing thread is not available, a new thread is created and added to the pool. Terminates and removes from the cache those threads that have not been used for 60 seconds.

 Public Static Executorservice Newsinglethreadexecutor ()

Create a single-threaded executor.

 Public Static Scheduledexecutorservice newscheduledthreadpool (int corepoolsize)

Create a thread pool that supports timed and recurring task executions, which in most cases can be used to replace the timer class.

Executor Executor = Executors.newfixedthreadpool (Tennew  Runnable () {    @Override      Public void run () {        System.out.println ("task over");     = Executors.newscheduledthreadpool (Ten, Ten, timeunit.seconds);

Second, executorservice and life cycle

Executorservice extends the executor and adds some life-cycle management methods. A executor life cycle has three states, runs , closes , and terminates . Executor is in a running state when it is created. When Executorservice.shutdown () is called, the IsShutDown () method returns true after the shutdown state. At this point, you should not want to add a task in executor, after all the added tasks are completed, executor is in the terminating state, isterminated () returns True.

If executor is turned off, submitting a task to executor throws unchecked exception rejectedexecutionexception.

Executorservice Executorservice = (executorservice) executor;  while (! Executorservice.isshutdown ()) {    try  {        executorservice.execute (Task);     Catch (Rejectedexecutionexception ignored) {            }}executorservice.shutdown ();

Iii. using Callable,future to return results

Future<v> represents an asynchronous operation, with the Get () method to get the result of the operation, and if the asynchronous operation is not completed, get () blocks the current thread. The futuretask<v> implements Future<v> and runable<v>. Callable represents one with a return worth operation.

callable<integer> func =NewCallable<integer>(){             PublicInteger Call ()throwsException {System.out.println ("Inside Callable"); Thread.Sleep (1000); return NewInteger (8);                }                }; Futuretask<Integer> Futuretask =NewFuturetask<integer>(func); Thread Newthread=NewThread (Futuretask);                Newthread.start (); Try{System.out.println ("Blocking Here"); Integer result=Futuretask.get ();        SYSTEM.OUT.PRINTLN (result); } Catch(Interruptedexception ignored) {}Catch(Executionexception ignored) {}

Executoreservice provides the submit () method, passing a callable, or runnable, back to the future. If the executor background thread pool has not completed the calculation of callable, this call returns the Get () method of the future object, blocking until the calculation is complete.

Example: Parallel computation of the and of arrays.

 PackageExecutorservice;Importjava.util.ArrayList;Importjava.util.List;Importjava.util.concurrent.Callable;Importjava.util.concurrent.ExecutionException;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;Importjava.util.concurrent.Future;ImportJava.util.concurrent.FutureTask; Public classConcurrentcalculator {PrivateExecutorservice exec; Private intCpucorenumber; Privatelist<future<long>> tasks =NewArraylist<future<long>>(); //Inner class    classSumcalculatorImplementsCallable<long> {        Private int[] numbers; Private intstart; Private intend;  PublicSumcalculator (Final int[] numbers,intStartintend) {             This. Numbers =numbers;  This. Start =start;  This. end =end; }         PublicLong Call ()throwsException {Long sum= 0l;  for(inti = start; I < end; i++) {sum+=Numbers[i]; }            returnsum; }    }     PublicConcurrentcalculator () {Cpucorenumber=runtime.getruntime (). Availableprocessors (); EXEC=Executors.newfixedthreadpool (Cpucorenumber); }     PublicLong sum (Final int[] numbers) {        //split tasks based on number of CPU cores, create futuretask and submit to executor         for(inti = 0; i < Cpucorenumber; i++) {            intincrement = Numbers.length/cpucorenumber + 1; intstart = increment *i; intend = Increment * i +increment; if(End >numbers.length) End=numbers.length; Sumcalculator Subcalc=Newsumcalculator (numbers, start, end); Futuretask<Long> task =NewFuturetask<long>(SUBCALC);            Tasks.add (Task); if(!Exec.isshutdown ())            {Exec.submit (Task); }        }        returnGetResult (); }    /*** Iterate through each task, get part sum, add back * *@return     */     Publiclong GetResult () {Long result= 0l;  for(future<long>task:tasks) {            Try {                //block If the calculation is not completedLong subsum =Task.get (); Result+=subsum; } Catch(interruptedexception e) {e.printstacktrace (); } Catch(executionexception e) {e.printstacktrace (); }        }        returnresult; }     Public voidClose () {Exec.shutdown (); }}

Main

int New int [] {1, 2, 3, 4, 5, 6, 7, 8, ten, one };   New concurrentcalculator ();   = calc.sum (numbers);  SYSTEM.OUT.PRINTLN (sum);  Calc.close ();  

Iv. Completionservice

In the first example, the GetResult () method iterates over an array of futuretask, and if the task is not completed then the current thread blocks, and if we want the result to be added to result when the arbitrary word task is completed, instead of waiting for each task to complete sequentially, Can make completionservice. The task performed by the producer submit (). The consumer take () completed tasks and processes their results in the order in which they were completed. That is, the take method of calling Completionservice is to return the result of putting the task back in the complete order, Completionservice internally maintains a blocking queue blockingqueue, and if no task is completed, the Take () method is blocked. To modify just the example using Completionservice:

 Public classConcurrentCalculator2 {PrivateExecutorservice exec; PrivateCompletionservice<long>Completionservice; Private intCpucorenumber; //Inner class    classSumcalculatorImplementsCallable<long> {        ......    }  PublicConcurrentCalculator2 () {Cpucorenumber=runtime.getruntime (). Availableprocessors (); EXEC=Executors.newfixedthreadpool (Cpucorenumber); Completionservice=NewExecutorcompletionservice<long>(exec); }     PublicLong sum (Final int[] numbers) {        //split tasks based on number of CPU cores, create futuretask and submit to executor         for(inti = 0; i < Cpucorenumber; i++) {            intincrement = Numbers.length/cpucorenumber + 1; intstart = increment *i; intend = Increment * i +increment; if(End >numbers.length) End=numbers.length; Sumcalculator Subcalc=Newsumcalculator (numbers, start, end); if(!Exec.isshutdown ())            {Completionservice.submit (SUBCALC); }                    }        returnGetResult (); }    /*** Iterate through each task, get part sum, add back * *@return     */     Publiclong GetResult () {Long result= 0l;  for(inti = 0; i < Cpucorenumber; i++) {                        Try{Long subsum=Completionservice.take (). get (); Result+=subsum; } Catch(interruptedexception e) {e.printstacktrace (); } Catch(executionexception e) {e.printstacktrace (); }        }        returnresult; }     Public voidClose () {Exec.shutdown (); }}

Java Concurrency Programming Executor

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.