Android thread pool to manage threads

Source: Internet
Author: User

Android thread pool to manage threads

There are many examples of thread pools on the Internet. In our actual application, for example, how to manage an application thread, we can say that we can use a thread pool to manage threads.

Eg:

Class DianLiang1 implements Runnable {

@ Override

Punlic void Run {

System. println ("*************** 111111111111111111111 ****************");

}

}

 

Class DianLiang2 implements Runnable {

@ Override

Punlic void Run {

System. println ("**************** 222222222222222222222222 **************");

}

}

Class DianLiang3 implements Runnable {

@ Override

Punlic void Run {

System. println ("**************** 222222222222222222222222 **************");

}

}

Public void main () {public static void main (String [] args ){
DianLiang1 t1 = new DianLiang1 (); DianLiang1 t1 = new DianLiang1 ();
DianLiang1 t1 = new DianLiang1 ();
T1. start ();
T2.start (); t3.start ();}
} The question is:

If you say: in the entrance:

If there are multiple threads, there are 100 threads so that the thread cannot be controlled.

At this time, we 'd better use the thread pool to manage threads.

The basic idea of the thread pool is also the idea of an object pool, which opens up a piece of memory space and stores a large number of threads (not dead). The thread execution scheduling in the pool is handled by the pool manager. When there is a thread task, take one from the pool. After the execution is complete, the thread object is returned to the pool. This avoids the performance overhead caused by repeated creation of thread objects and saves system resources.

For example, an application needs to deal with the network and there are many steps to access the network. In order not to block the main thread, each step creates a thread to interact with the network in the thread, the use of the thread pool becomes simple. The thread pool is an encapsulation of the thread, making it easier to use the thread. You only need to create a thread pool, put these steps into the thread pool like a task. When the program is destroyed, you only need to call the destroy function of the thread pool.


There are three common java thread pools:
  • NewFixedThreadPool
    Create a thread pool that can reuse a fixed number of threads and run these threads in a shared, unbounded queue mode. At any point, most nThreads threads are in the active state of processing tasks. If an additional task is submitted when all threads are active, the additional task will wait in the queue before there is an available thread. If any thread is terminated due to a failure during the execution before it is disabled, a new thread will execute subsequent tasks (if needed) in place of it ). Before a thread is explicitly disabled, the thread in the pool will always exist.
    ExecutorService pool = Executors. newFixedThreadPool (2 );
    // Create and implement the Runnable interface object, and the Thread object also implements the Runnable interface.
    Thread t1 = new MyThread ();
    Thread t2 = new MyThread ();
    Thread t3 = new MyThread ();
    Thread t4 = new MyThread ();
    Thread t5 = new MyThread ();
    // Put the thread into the pool for execution
    Pool.exe cute (t1 );
    Pool.exe cute (t2 );
    Pool.exe cute (t3 );
    Pool.exe cute (t4 );
    Pool.exe cute (t5 );
    • NewSingleThreadExecutor
      Create an Executor that uses a single worker thread to run this thread in an unbounded queue mode. (Note: If this single thread is terminated because of a failure during the execution before it is disabled, a new thread will execute subsequent tasks in place of it if needed ). The tasks can be executed sequentially, and no threads are active at any given time. Unlike other equivalent newFixedThreadPool (1), other threads can be used without the need to reconfigure the execution program returned by this method.
      • NewCachedThreadPool

        Create a thread pool where new threads can be created as needed, but they will be reused when previously constructed threads are available. For programs that execute many short-term asynchronous tasks, these thread pools can usually improve program performance. Calling execute will reuse the previously constructed thread (if the thread is available ). If the existing thread is not available, create a new thread and add it to the pool. Terminate and Remove unused threads from the cache for 60 seconds. Therefore, a thread pool that remains idle for a long time does not use any resources. Note: You can use the ThreadPoolExecutor constructor to create a thread pool with similar attributes but different details (such as timeout parameters.

         

        The reprinted content is as follows:

         

        ThreadPoolExecutor (int corePoolSize, int maximumPoolSize, long keepAliveTime,

        TimeUnit unit, BlockingQueue WorkQueue, RejectedExecutionHandler handler)

        CorePoolSize: Minimum number of threads maintained by the thread pool maximumPoolSize: Maximum number of threads maintained by the thread pool keepAliveTime: the idle time allowed by the thread pool maintenance thread

        Unit: the unit of idle time allowed by the thread pool to maintain the thread. workQueue: The Buffer Queue handler used by the thread pool: The processing policy of the thread pool to reject tasks.

        A task is added to the thread pool using the execute (Runnable) method. A task is a Runnable object. The execution method of a task is the run () method of a Runnable object.

        When a task is added to the thread pool through the execute (Runnable) method:

        L if the number of threads in the thread pool is smaller than corePoolSize at this time, a new thread should be created to process the added tasks even if all threads in the thread pool are idle.

        2. If the number in the thread pool is equal to corePoolSize but the Buffer Queue workQueue is not full, the task is put into the buffer queue.

        3. If the number in the thread pool is greater than corePoolSize, the Buffer Queue workQueue is full, and the number in the thread pool is smaller than maximumPoolSize, a new thread is created to process the added task.

        4. If the number in the thread pool is greater than corePoolSize, the Buffer Queue workQueue is full, and the number in the thread pool is equal to maximumPoolSize, the handler policy is used to process the task. That is, the processing task priority is: Core Thread corePoolSize, task queue workQueue, maximumPoolSize. If all three are full, handler is used to process the rejected task.

        5. When the number of threads in the thread pool is greater than corePoolSize, if the idle time of a thread exceeds keepAliveTime, the thread will be terminated. In this way, the thread pool can dynamically adjust the number of threads in the pool.

         

        An ExecutorService that uses one of several possible pool threads to execute each submitted task. It is usually configured using the Executors factory method.

        The thread pool can solve two different problems: because it reduces the overhead of each task call, they can generally provide enhanced performance when executing a large number of asynchronous tasks, you can also bind and manage resources (including the threads used to execute collection tasks. Each ThreadPoolExecutor also maintains some basic statistics, such as the number of completed tasks.

        This class provides many adjustable parameters and extension hooks for ease of use across a large number of contexts. However, it is strongly recommended that programmers use the more convenient Executors factory method Executors. newCachedThreadPool () (unbounded thread pool, which can be automatically recycled), Executors. newFixedThreadPool (int) (fixed-size thread pool) and Executors. newSingleThreadExecutor () (a single background thread), which are predefined for most use cases. Otherwise, use the following instructions when manually configuring and adjusting the class:

        Core and maximum pool size

        ThreadPoolExecutor automatically adjusts the pool size based on the boundaries set by corePoolSize (see getCorePoolSize () and maximumPoolSize (see getMaximumPoolSize. When a new task is submitted in the execute (java. lang. Runnable) method, if the running thread is less than corePoolSize, a new thread is created to process the request, even if other auxiliary threads are idle. If the number of running threads is greater than corePoolSize and less than maximumPoolSize, a new thread is created only when the queue is full. If the set corePoolSize and maximumPoolSize are the same, a fixed thread pool is created. If you set maximumPoolSize to a basic unbounded value (such as Integer. MAX_VALUE), the pool is allowed to adapt to any number of concurrent tasks. In most cases, the core and maximum pool sizes are only set based on the constructor. However, you can also use setCorePoolSize (int) and setMaximumPoolSize (int) for dynamic changes.

        Construct on demand

        By default, you can use the prestartCoreThread () or prestartAllCoreThreads () method to dynamically override the Core Thread created and started only when the new task is required.

        Create a thread

        Use ThreadFactory to create a new thread. Otherwise, Executors. defaultThreadFactory () is used to create threads in the same ThreadGroup, and these threads have the same NORM_PRIORITY priority and non-daemon status. By providing different ThreadFactory, you can change the thread name, thread group, priority, and daemon status. If ThreadFactory fails to create a thread when return null from newThread, the execution program continues to run, but cannot execute any tasks.

        Maintain activity time

        If there are more threads in the pool than corePoolSize, these extra threads will be terminated when the idle time exceeds keepAliveTime (see getKeepAliveTime (java. util. concurrent. TimeUnit )). This provides a way to reduce resource consumption when the pool is inactive. If the pool becomes more active later, a new thread can be created. You can also use setKeepAliveTime (long, java. util. concurrent. TimeUnit) to dynamically change this parameter. Use the value of Long. MAX_VALUE TimeUnit. NANOSECONDS to effectively disable idle threads from the previous termination status before closing.

        Queuing

        All BlockingQueue can be used to transfer and maintain submitted tasks. You can use this queue to interact with the pool size:

        A. If the number of running threads is less than corePoolSize, Executor always prefers to add new threads without queuing.

        B. If the running thread is equal to or greater than corePoolSize, Executor always prefers to add requests to the queue without adding new threads.

        C. If the request cannot be added to the queue, a new thread is created, unless the creation of this thread exceeds the maximumPoolSize. In this case, the task is denied.

        There are three common queuing policies:

        Submit directly. The default Job Queue option is SynchronousQueue, which directly submits tasks to the thread without holding them. If there is no thread that can be used to run the task immediately, trying to add the task to the queue will fail, so a new thread will be constructed. This policy prevents locking when processing a collection of requests that may have internal dependencies. Direct submission usually requires unbounded maximumPoolSizes to avoid rejecting new tasks. This policy allows unbounded threads to grow when the command arrives continuously beyond the average number that the queue can handle.

        Unbounded queues. The use of unbounded queues (for example, blockingqueue with no predefined capacity) will cause new tasks to be added to the queue when all corePoolSize threads are busy. In this way, the created thread will not exceed the corePoolSize. (Therefore, the value of maximumPoolSize is invalid .) When each task is completely independent from other tasks, that is, the task execution does not affect each other, it is applicable to the use of unbounded queues; for example, in the Web Page Server. This kind of queuing can be used to handle transient bursts of requests. This policy allows unbounded threads to grow when the command arrives continuously beyond the average number that the queue can handle.

        Bounded queue. When a limited number of maximumPoolSizes are used, a bounded Queue (such as ArrayBlockingQueue) helps prevent resource depletion, but may be difficult to adjust and control. The queue size and the maximum pool size may need to be compromised: using large queues and small pools can minimize CPU usage, operating system resources, and context switching overhead, but may cause manual throughput reduction. If the tasks are frequently congested (for example, if they are I/O boundaries), the system may schedule a longer time than you permit for more threads. Using a small queue usually requires a large pool size, and the CPU usage is high, but it may encounter unacceptable scheduling overhead, which will also reduce the throughput.

        Rejected task

        When the Executor has been disabled and the Executor uses the finite boundary for maximum thread and work queue capacity, and is saturated, execute (java. lang. runnable. In both cases, the execute method calls the RejectedExecutionHandler's RejectedExecutionHandler. rejectedExecution (java. lang. Runnable, java. util. concurrent. ThreadPoolExecutor) method. The following provides four predefined handler policies:

        A. in the default ThreadPoolExecutor. AbortPolicy, A running RejectedExecutionException will be thrown if the handler is rejected.

        B. In ThreadPoolExecutor. CallerRunsPolicy, the thread calls the execute itself that runs the task. This policy provides a simple feedback control mechanism to speed down the submission of new tasks.

        C. In ThreadPoolExecutor. DiscardPolicy, tasks that cannot be executed will be deleted.

        D. In ThreadPoolExecutor. DiscardOldestPolicy, if the execution program is not closed, the task in the Job Queue header will be deleted, and then the execution program will be retried (if the execution fails again, the process will be repeated ).

        Defining and using other types of RejectedExecutionHandler classes is also possible, but you need to be very careful when doing so, especially when the policy is only used for a specific capacity or queuing policy.

        Hook method

        This class provides the rewritable beforeExecute (java. lang. thread, java. lang. runnable) and afterExecute (java. lang. runnable, java. lang. throwable) method. These two methods are called before and after each task is executed. They can be used to manipulate the execution environment; for example, reinitializing ThreadLocal, collecting statistics, or adding log entries. In addition, you can override the terminated () method to execute all the special processing that needs to be completed after the Executor is completely terminated.

        If an exception is thrown by the hook or callback method, the Internal auxiliary thread will fail and terminate suddenly.

        Queue Maintenance

        The getQueue () method allows access to the work queue for monitoring and debugging purposes. It is strongly opposed to using this method for any other purpose. Remove (java. lang. Runnable) and purge () methods can be used to help with storage collection when a large number of queued tasks are canceled.

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.