Java multithreading (iii) Several thread pools implemented by-executors and callable

Source: Internet
Author: User
Tags stub

Starting with java5, many new APIs for managing scheduling threads have been introduced into the class library, most commonly the executor (actuator) Framework. Executor helps programmers manage thread objects and simplifies concurrent programming by providing a middle tier that allows programmers to manage the execution of asynchronous tasks without explicitly managing the life cycle of the THREADS.


Executor uses thread pooling implementations and is more cost-efficient because it is the preferred method for starting new THREADS.

Example Code: Src/thread_runnable/cachedthreadpool.java

1  public classcachedthreadpool{2     3      public Static voidmain (string[] Args) {4Executorservice exec =Executors.newcachedthreadpool ();5         6         7System.out.println ("main start" +thread.currentthread (). getName ());8          for(inti=0; i<3; i++){9Exec.execute (NewCountdown ());Ten         } one          a Exec.shutdown (); -System.out.println ("main end" +thread.currentthread (). getName ()); -     } the  -}

Output result: (different output results per Execution)

The executors class creates a thread pool by providing a series of factory methods, The returned thread pool implements the Executorservice interface, the Executorservice interface implements the executor interface, and provides a richer way to manage the thread Pool. The Executorservice object can begin execution of the new method (which itself is also part of the command design Pattern) through the Execute (Runnable)/submit (callable) method.

The life cycle of Executorservice (which is actually the thread Pool) consists of three states, running, closing, and Terminating. Once created, it goes into a running State. The shutdown () method is called to enter the shutdown State. At this point, Executorservice no longer accepts new tasks, but it is still performing the tasks that have already been submitted, and when all the tasks have been completed, it is Terminated.


The executors class creates a thread pool by providing a series of factory methods, common types are:

1  public Static Executorservice newfixedthreadpool (int Nthreads)

Create a fixed number of thread pools

1  public Static Executorservice Newcachedthreadpool ()

Creates a cacheable thread pool that, after calling execute to add a new task, reuses the thread if there are available threads that were previously constructed, or creates a new thread and adds it to the Pool. And you can remove threads that are not used by 60s from the Cache.

1  public Static Executorservice Newsinglethreadexecutor ()

Creates a single threaded pool of THREADS. In fact, there is only one thread, and all tasks are executed in the specified order, (fifo,lifo, priority).

1  public Static Scheduledexecutorservice newscheduledthreadpool (int Corepoolsize)

Create a fixed-line pool that supports timed and recurring task executions, so many times it can be used instead of the timer class.

See a simple example, code address: Src/thread_runnable/fixedthreadpool.java

1  public classfixedthreadpool{2      public Static voidmain (string[] Args) {3         intThreadCount = 2; 4Executorservice exec =Executors.newfixedthreadpool (threadcount);5         6System.out.println ("main start" +thread.currentthread (). getName ());7          for(inti=0; i<3; i++){8Exec.execute (NewCountdown ());9         }Ten Exec.shutdown (); oneSystem.out.println ("main end" +thread.currentthread (). getName ()); a          -     } -}

When threadcount = 2 o'clock, One time the output result is:

As can be seen from the output, at first, only Thread-1 and thread-2 two threads were performing the task, and when the previous task was completed, Thread-2 was reused to begin the third Task.
Then we can imagine that if we put threadcount = 1, Then there should only be one thread that performs one task and then executes the Other.
Modify ThreadCount = 1, The output matches our expectations:

Threads that can be executed periodically or delay are also more common in actual projects.
Example code address: Src\thread_runnable\scheduledexecutorservicedemo.java

1  public classScheduledexecutorservicedemo {2      public Static voidmain (string[] Args) {3         //TODO auto-generated Method Stub4Scheduledexecutorservice Mscheduledservice = Executors.newscheduledthreadpool (2);5System.out.println ("scheduledexecutorservicedemo---main start," +thread.currentthread (). getName ());6Mscheduledservice.schedule (NewCountdown (), 2, timeunit.seconds);7System.out.println ("scheduledexecutorservicedemo---main end," +thread.currentthread (). getName ());8 Mscheduledservice.shutdown ();9     }Ten}

Output: (through The actual output, you can see, two seconds later, only to start executing the print statements in the Task)

A demo of recurring tasks.
Example code address: Src\thread_runnable\scheduledfixedservicedemo_2.java

1  public classScheduledfixedservicedemo_2 {2      public Static voidmain (string[] Args) {3         //TODO auto-generated Method Stub4Scheduledexecutorservice Mscheduledservice = Executors.newscheduledthreadpool (2);5System.out.println ("scheduledfixedservicedemo_2---main start," +thread.currentthread (). getName ());6Mscheduledservice.schedulewithfixeddelay (NewRunnable () {7             intCount = 0;8 @Override9              public voidRun () {TenSystem.out.println ("fixed Print =" + count++); one                  a             } -}, 1, 2, timeunit.seconds); -System.out.println ("scheduledfixedservicedemo_2---main end," +thread.currentthread (). getName ()); the     } -}

Output result:

..... after each interval of 2s, output once.

Runnable Although the task is performed, but there is no return value, and after Java 5, a callable interface is reintroduced, which is a generic with a type parameter that represents the value returned from the call () Method. however, It should be noted that after passing the callable object to Executorservice's submit method, the call () method executed on the new thread returns the future object, which has a isdone (), get () and other methods to determine whether to complete, and to get the return Value.

Code Address: Src\thread_runnable\callabledemo.java

1 classTaskwithresultImplementsCallable<string> {2      publicString Call ()throwsException {3         return"result of Taskwithresult from callable" + "\ t" +thread.currentthread (). getName ();4     }5 }6 7 8  public classCallabledemo {9      public Static voidmain (string[] Args) {Ten         //TODO auto-generated Method Stub oneExecutorservice exec =Executors.newcachedthreadpool (); a          -System.out.println ("main start\t" +thread.currentthread (). getName ()); -Future<string> fs = Exec.submit (NewTaskwithresult ()); the Exec.shutdown (); -          -         Try { -             //This is always blocked when the callable object is not Finished.  + System.out.println (fs.get ()); -}Catch(Exception E) { + e.printstacktrace (); a         } atSystem.out.println ("main end\t" +thread.currentthread (). getName ()); -     }     -}


Output result:

Java multithreading (iii) Several thread pools implemented by-executors and callable

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.