Android multithreaded thread pool principle encapsulation thread pool __ Threads

Source: Internet
Author: User

I understand it myself. A thread pool is the meaning of a container, and it should be noted that each thread requires a CPU to allocate resources to execute. If you start a thread by always using new thread (), you will consume a lot of CPU resources, causing Android to run slowly, or even oom (out of memory), and Java will have a threadpoolexecutor to manage these threads. The number of threads that control the most maximumpoolsize the number of core threads corepoolsize to manage the number of threads we need to open. This reduces the number of times a thread is created and destroyed, and each worker thread can be reused to perform multiple tasks. Therefore, we can according to the phone's CPU core number to control the maximum number of threads app can open, to ensure the reasonable operation of the program. &NBSP
The introduction of thread pooling technology can greatly improve the performance of the app when multiple network threads are concurrent concurrently on Android. For example: Multithreading download, click a download (assuming that you can download up to five at the same time), when the point to the sixth time to start waiting, which involves the management of the thread. &NBSP
Android introduces the thread pool benefits are improved performance (creating and consuming objects costs CPU resources), preventing excessive memory consumption (controlling the number of active threads and preventing excessive concurrent threads). 1.ThreadPoolExecutor 1.ThreadPoolExecutor parameter

The JDK itself has a thread pool implementation class Threadpoolexecutor, and using threadpoolexecutor to understand the meaning of each of its parameters is essential.
Threadpoolexecutor (Corepoolsize, maximumpoolsize, KeepAliveTime, Unit, Workqueue, Threadfactory, Handler)
Corepoolsize: Core number of threads, the number of tasks that can be executed concurrently;
Maximumpoolsize: To remove the waiting tasks in the buffer queue, the maximum number of tasks to accommodate (in fact, including the number of core thread pool);
KeepAliveTime: Beyond the Workqueue waiting task of survival time, refers to the maximumpoolsize inside the waiting task survival time;
Unit: time units;
Workqueue: Block waiting thread queue, general use of new Linkedblockingqueue () This, if not specified capacity, will be added to the inside, there is no limit, workqueue will never be full;
Threadfactory: The factory that creates the thread, uses the system default class;
Handler: When the number of tasks exceeds maximumpoolsize, the default policy is to reject the add; 2. Blocking Queues

Queues are used to queue to avoid problems with a large number of requests in a flash.
The blocking queues are divided into finite queues (Synchronousqueue, arrayblockingqueue) and infinite Queues (linkedbloackingqueue). 3. Implementation process

When the number of threads is less than corepoolsize, thread execution is immediately opened, and when Corepoolsize is full, the tasks added later are placed in the buffer queue Workqueue wait; When Workqueue is full, See if the number of maximumpoolsize threads is exceeded, default is refused.
Let's take a look at an example: if the corepoolsize=2,maximumpoolsize=3,workqueue capacity is 8; At the very beginning, the task performed a,b, at this time Corepoolsize has run out, and the task C is executed again. Then C will be placed in the buffer queue Workqueue waiting, if later added 7 tasks, at this time Workqueue full, then the next task will be compared with maximumpoolsize, because Maximumpoolsize is 3, so can only accommodate 1, Because there are 2 of them running in corepoolsize, the tasks that come after them are rejected by default. 4. Terminate a thread

We write a JUnit test method that terminates a thread:

Private class Myrunnable implements Runnable {public
    volatile Boolean flag = true;
    @Override public
    Void Run () {while
        flag &&! Thread.interrupted ()) {
            try {
                System.out.println ("Running");
                Thread.Sleep (+);
            } catch (Interruptedexception e) {
                e.printstacktrace ();
                Return 2. When the thread is disconnected, note that the processing must be done here}}}
        @Test public
void Runnabletest () throws interruptedexception {
    myrunnable runnable = new myrunnable ();
    Thread thread = new Thread (runnable);
    Thread.Start ();
    Thread.Sleep ();
    Runnable.flag = true;
    Thread.Interrupt (); 1. Interrupt Thread
}
2. Package thread pool Manager

Below we encapsulate the thread pool based on Threadpoolexecutor:

/** * thread pool management manages all threads in the entire project, so there can be no more than one instance object/public class Threadpoolmanager {/** * Singleton design mode (a Hungry man) * Single case first privatization construction method,
    The A hungry man then begins to create and provides a Get method/private static Threadpoolmanager minstance = new Threadpoolmanager ();
    public static Threadpoolmanager getinstance () {return minstance;
    The number of private int corepoolsize;//core thread pools, while the number of threads capable of executing private int maximumpoolsize;//The maximum number of thread pools, indicating the number of wait tasks that can continue to hold when the buffer queue is full
    Private Long KeepAliveTime = 1;//survival time private timeunit unit = timeunit.hours;
    Private Threadpoolexecutor executor;
         Private Threadpoolmanager () {/** * assigns value to Corepoolsize: Current device available processor core number *2 + 1, to maximize CPU efficiency (with research argument)
        * * corepoolsize = Runtime.getruntime (). Availableprocessors () *2+1; Maximumpoolsize = corepoolsize; Although Maximumpoolsize is not used, it needs to be assigned a value, otherwise the error executor = new Threadpoolexecutor (corepoolsize,//When a core task is executed, Will then take the wait task out of the buffer queue maximumpoolsize,//5, first corepoolsize, then new linkedBlockingqueue<runnable> (), then maximumpoolsize, but its number is contained corepoolsize KeepAliveTime,//represented by Maximumpool Size in which to wait for the task of survival Unit, New linkedblockingqueue<runnable> (),//buffer queue, used to store waiting tasks, linked first Enter first out executors.defaultthreadfactory (),///create a thread of the factory new Threadpoolexecutor.abortpolicy ()//To
    Beyond the maximumpoolsize of the task of the processing strategy);

        /** * Execute task */public void execute (Runnable Runnable) {if (runnable==null) return;
    Executor.execute (runnable);

        /** * Remove Task/public void Remove (Runnable Runnable) {if (Runnable==null) return from the thread pool;
    Executor.remove (runnable); }
}
Where to get the current number of processor cores available we use Runtime.getruntime (). Availableprocessors (), we look at its comments:

Now let's take a look at the difference between runnable and threading:
Runnable is just an interface, its source code is as follows, while the thread is really open system resources to perform tasks, both of them, threads are really consuming system resources

/**
 * Represents a command that can be executed. Often used to run code in a
 * different {@link Thread}.
 * * Public
interface Runnable {
    /**
     * Starts executing the active part of the class ' Code. This are
     * called when a thread is started that has been created with a class which
     * Implements {@code Runn Able}.
     *
    /public void run ();
}

We've basically covered the thread pool here, so let's look at how to use the thread pool with the actual code. 3. How to use the demo thread pool

The following is an example of a thread pool (demonstrating multithreaded execution tasks) to deepen understanding of the principles
1. Introduce our packaged Threadpoolmanager.java
2. Demo function

/**
 * Demo thread pool/public
class Mainactivity extends Appcompatactivity {
    @Override
    protected void OnCreate (Bundle savedinstancestate) {
        super.oncreate (savedinstancestate);
        Setcontentview (r.layout.activity_main);
        /**
         * Create nine tasks *
        /for (int i = 0; i < 9; i++) {
            threadpoolmanager.getinstance (). Execute (New DOWNLOADTA SK (i));
        }
    /**
     * Imitate the download task, realize Runnable *
    /class Downloadtask implements runnable{
        private int num;
        public downloadtask (int num) {
            super ();
            This.num = num;
            LOG.D ("JAVA", "task-" +num + "Wait ...");
        }
        @Override public
        Void Run () {
            log.d ("JAVA", "task-" +num + "begins executing ...) began to carry out ... ");
            Systemclock.sleep (5000); Simulate time delay execution
            log.e ("JAVA", "task-" +num + "ends ...");}}
Print the results as follows:



Reprint: http://blog.csdn.net/smartbetter/article/details/52056272

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.