Java Android Executorservice thread pool parsing

Source: Internet
Author: User
Tags terminates


Executorservice:

It is also an interface that extends from the executor interface, and the executor interface is more like an abstract command pattern, with only one side Law: Execute (runnable); Executor interface is simple, but important, important in this design mode. after Java5, the executor to start the line turndown with the thread start () is better. In the new feature, it is easy to control the threading startup, execution, and shutdown processes, and it is easy to use the thread pool features.


Several different executorservice thread pool objects

1.newCachedThreadPool ()
-Cache pool, first see if there are no previously established threads, if any, reuse. If not, create a new thread to join the pool
-the thread that can be reuse, must be in timeout idle in the pool thread, the default timeout is 60s, more than this idle time, the thread instance will be terminated and removed from the pool.
  Note that the thread that is put into the cachedthreadpool does not have to worry about its end, exceeding timeout inactivity, which is automatically terminated.
2. Newfixedthreadpool
-newfixedthreadpool and Cachethreadpool are similar, but also can reuse use, but can not build new threads at any time
-its uniqueness: At any point in time, there can be at most a fixed number of active threads, and if a new thread is to be established, it can only wait in another queue until a thread in the current thread terminates and is moved out of the pool directly .
-unlike Cachethreadpool, Fixedthreadpool does not have an idle mechanism (possibly, but since the document is not mentioned, it must be very long, similar to the TCP or UDP idle mechanism that relies on the upper layer), So Fixedthreadpool most for some very stable and fixed regular concurrent threads, more for the server
-from the source of the method, the cache pool and the fixed pool call the same underlying pool, except that the parameters are different:
Fixed pool thread count, and is 0 seconds idle (no idle)
Cache Pool Threads Support 0-integer.max_value (obviously not considering the host's resource tolerance), 60 seconds idle 

3.ScheduledThreadPool
-Scheduling thread pool
-the thread in this pool can be executed by schedule, or cycle execution

4.SingleThreadExecutor
-Single thread, only one thread in any time pool
-Use the same underlying pool as the cache pool and the fixed pool, but the number of threads is 1-1, 0 seconds idle (no idle)


1, Executorservice:

is an interface that inherits the executor:

 Public Interface extends Executor {}
2, Executor:

The executor is also an interface that contains only one method:

void Execute (Runnable command);
3, Executors:

This class is an auxiliary class that is defined in this package as Executor, Executorservice, Scheduledexecutorservice, Threadfactory, and callable classes of factories and utility methods.

This class supports the following various methods:

? Creates and returns a method that sets the executorservice of a common configuration string.
? Creates and returns a method that sets the scheduledexecutorservice of a common configuration string.
? Creates and returns a "wrapped" Executorservice method that disables reconfiguration by making the implementation-specific method inaccessible.
? Creates and returns a Threadfactory method that sets the newly created thread to a known state.
? A method that creates and returns a callable in the form of a non-closed packet, which can be used in an execution method that requires callable. 4, the method of creating Executorservice:
Newfixedthreadpool ()

Create a thread pool that reuses the number of fixed threads and run them in a shared, unbounded queue.

5, the method of Executorservice:shutdown
shutdown ()
Starts a sequential shutdown, performs a previously submitted task, but does not accept new tasks. If it is already closed, the call has no other effect.

Thrown:
SecurityException -If the security manager exists and shuts down, this executorservice may operate on some thread that does not allow the caller to modify it (because it is not persisted RuntimePermission ("Modifythread")), or the security manager's The checkAccess method denies access.

Starts a sequential shutdown, performs a previously submitted task, but does not accept new tasks. If it is already closed, the call has no other effect.

awaittermination
awaittermination (Long timeout,                         Timeunit unit)                         throws Interruptedexception
A request is closed, a timeout occurs, or when the front thread is interrupted, whichever occurs first, it will cause blocking until all tasks have completed execution.

timeout  -maximum wait time
unit  -Time Unit of timeout parameter
return:
If this executor terminates, return   true If timeout expires before termination, &NBSP is returned; false
thrown:
interruptedexception  -If an interrupt occurs while waiting /span>

A request is closed, a timeout occurs, or when the front thread is interrupted, whichever occurs first, it will cause blocking until all tasks have completed execution. Both wait for all child threads to finish executing.

Execute
Execute (Runnable command)
Executor implementation.  

parameters:/ span>
command  -tasks to run
thrown:
rejectedexecutionexception  -If you cannot accept this task.
nullpointerexception  -If the command is NULL

Executes the given command at some time in the future. The command may be executed in a new thread, a thread that is in the pool, or a thread that is being invoked, as determined by the Executor implementation.

Submit
Submit (Runnable Task)
submits a Runnable task for execution and returns a future that represents the task. The get method for the future will return nullupon successful completion.

task  -task to submit
return:
thrown:
rejectedexecutionexception  -If the task cannot be scheduled to execute
nullpointerexception  -If the task is null

Submits a Runnable task for execution and returns a future that represents the task. The Get method for the future will return null upon successful completion.

6, the following are the relevant use examples:
 Public classexecutorservicetest { Public Static voidMain (string[] args)throwsIOException, Interruptedexception {//Create a fixed-size thread poolExecutorservice Service = Executors.newfixedthreadpool (3); for(inti = 0; I < 10; i++) {System.out.println ("Create thread"+ i); Runnable Run =NewRunnable () {@Override                 Public voidRun () {System.out.println ("Start Thread"); }            };//execute the given command at some time in the futureService.execute (run); }//Shut down boot threadService.shutdown ();//wait for the child thread to finish before continuing with the following codeService.awaittermination (Long.max_value, timeunit.days); System.out.println ("All thread Complete"); }}

The thread can be found to be created by looping, but the startup thread is not sequential, but is determined by Executorservice.

Reference: http://www.itzhai.com/the-executorservice-common-method-newfixedthreadpool-of-create-fixed-size-thread-pool.html

If you have any questions, please leave a message, reproduced the source.


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.