Java Concurrency and Multithreading 1: A basic example of a concurrency framework (. txt)

Source: Internet
Author: User


The Executor framework refers to a number of Executor-related functional classes in a series of concurrency libraries introduced in Java 5, including Threadpool,executor,executors,executorservice, Completionservice,future,callable and so on.


A programming method for concurrent programming is to split a task into a series 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.


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, the task should not be added to executor, and after all the added tasks have been executed, executor is in the signaled state, isterminated () returns True.
If executor is turned off, submitting a task to executor throws unchecked exception rejectedexecutionexception.


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.


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.


Iv. Code Examples
Package Cn.fansunion.executorframework;import Java.util.concurrent.callable;import Java.util.concurrent.executionexception;import Java.util.concurrent.executor;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import Java.util.concurrent.futuretask;import java.util.concurrent.rejectedexecutionexception;//concurrency Framework Several examples demonstrate public class Executorframeworkdemo {public static Runnable task = new Runnable () {@Overridepublic void run () {System.out.println ("Exec Ute a Task ");}};/ /Use only 1 worker threads, perform task public static void Singlethreadexecutor () {Executor Executor = Executors.newsinglethreadexecutor (); Executor.execute (Task);} The thread pool that has a fixed number of threads public static void Fixedthreadpool () {Executor Executor = Executors.newfixedthreadpool (10); Executor.execute (Task);} A executor life cycle has three states, runs, closes, terminates public static void Executorlifecycle () {Executorservice Executorservice = Executors.newscheduledthreadpool (), if (!executorservice.isshutdown ()) {try {Executorservice.execute (Task);} catch (rejecteDexecutionexception e) {e.printstacktrace ();}} Executorservice.shutdown ();} Future<v> represents an asynchronous operation, and the result of the operation is obtained through the Get () method.//If the asynchronous operation has not yet completed, get () blocks the current thread. The futuretask<v> implements Future<v> and runable<v>. Callable represents one with a return worth operation. private static void Futurecalable () {callable<integer> func = new callable<integer> () {public Integer call () t Hrows Exception {System.out.println ("inside callable"); Thread.Sleep (+); integer n = new integer (8); return n;}}; futuretask<integer> futuretask = new Futuretask<integer> (func); Thread newthread = new Thread (futuretask), Newthread.start (), try {System.out.println ("blocking Here"), Integer result = Futuretask.get (); SYSTEM.OUT.PRINTLN (result);} catch (Interruptedexception ignored) {} catch (Executionexception ignored) {}}public static void main (string[] args) {Sing Lethreadexecutor (); Fixedthreadpool (); executorlifecycle (); futurecalable ();}}



More code Examples:
Http://git.oschina.net/fansunion/Concurrent (in gradual update)


Resources:
Java Concurrency Programming-executor framework
http://www.iteye.com/topic/366591

Java Concurrency and Multithreading 1: A basic example of a concurrency framework (. txt)

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.