Android Threads and thread pools

Source: Internet
Author: User

As we all know, in the UI system to do some time-consuming operation, will lead to lag phenomenon, because a refresh at 16ms, if the time after the operation, then users can feel the obvious lag, even caused the ANR.
In this case, it is common to start a thread, take some time-consuming operations, by inheriting the thread or implementing the Runnable interface, overriding the Run method, to implement the creation of a new thread, The need for time-consuming operations. Because of Java's single-inheritance relationship, the first push implements the Runnable method, which is not too bloated.

  private void Runthread () {Thread T1 = new Thread (new myrunnable (This), "Aaron Kwok");      T1.start ();    As a point of emphasis, calling the Run method is a real call to the method, and invoking the Start method creates a new thread to invoke the Run method. }//implement Runnable method as for the code that inherits the thread method, it does not write the static class Myrunnable implements Runnable {private Weakreference<ma        Inactivity> reference;        Myrunnable (mainactivity activity) {reference = new weakreference<mainactivity> (activity); } @Override public void Run () {if (reference! = NULL) {mainactivity activity = R                Eference.get ();                    if (activity! = NULL) {//child thread cannot play toast so add something looper.prepare ();                    Toast.maketext (activity, Thread.CurrentThread (). GetName () + "is runing", Toast.length_short). Show ();                Looper.loop (); }            }        }    }

In addition, after the jdk1.5 version, a new callable interface, compared to the runnable interface, he can define the return value, and can throw an exception, the need to implement the method also from the Run method into the call method. It is also interesting that he returns a future object through which we can know the program of the task and can close the task. Thread does not support this interface, so if you want to use callable, you need to use Futuretask.

@FunctionalInterfacepublic interface Callable<V> {    V call() throws Exception;}public interface Future<V> {    boolean cancel(boolean mayInterruptIfRunning);    boolean isCancelled();    boolean isDone();    V get() throws InterruptedException, ExecutionException;    V get(long timeout, TimeUnit unit)        throws InterruptedException, ExecutionException, TimeoutException;}

Simply put, Futuretask is an asynchronous task that can be canceled, asynchronously executing a task, can start, cancel, and see if the task is complete, and if the task is not finished, the Get method causes the thread to block, and once a task has been completed it cannot start and end again ( Unless executed through the Runandreset () method. In addition, Futuretask also supports runnable interfaces.

 private void Runfuturetask () {//create thread pool without thread pool directly with the future can also final executorservice exec = Executors.newfixedt        Hreadpool (5);        Create Futuretask Task final futuretask<string> ft = new futuretask<string> (new Mycallable ());        Execution can also be submitted or there is a InvokeAll method Exec.execute (FT);//Exec.submit (FT); New Thread (New Runnable () {@Override public void run () {try {// The Get method automatically blocks the current thread until the result is received//so do not put it on the main thread to get it or it will get stuck, even though I tried it for 15 seconds. Final String text = FT.G                    ET ();                    Looper.prepare ();                    Toast.maketext (futuretaskactivity.this, Text, Toast.length_short). Show ();                Looper.loop ();                } catch (Interruptedexception e) {e.printstacktrace ();                } catch (Executionexception e) {e.printstacktrace ();        }}). Start (); Run out of threadsPool remember to close off Exec.shutdown (); } Static class Mycallable implements callable<string> {@Override public String call () throws Excep            tion {thread.sleep (3000);        Return "Code makes me Happy, code makes me bald"; }    }

Thread is the smallest unit of CPU scheduling, for thread creation, destruction, scheduling, in fact, is also a resource-intensive, especially in some cases, you need to create a bunch of threads to do some simple time-consuming operation, the resource consumption is very large, so the needs of the cable pool.

Let's summarize the pros.
1. Reuse threads in the thread pool to avoid the frequent creation and destruction of performance consumed by threads;
2. Effectively control the maximum number of concurrent threads, prevent the thread from being too large causing the system to block the preemption resource;
3. Threads can be managed in a certain way.

Use line Cheng for each new thread, the performance will be much better, and can be unified management, function can also improve, if need to execute regularly, regular execution, thread interruption and so on.
Reduce memory overhead.

Threadpoolexecutor:executorservice is the initial thread pool interface, the Threadpoolexecutor class is a concrete implementation of the thread pool, it constructs the method to configure the thread pool parameters, let us analyze its common constructor. Public threadpoolexecutor (int corepoolsize, int maximumpoolsize, long ke    Epalivetime, Timeunit Unit, blockingqueue<runnable> workQueue) { This (Corepoolsize, maximumpoolsize, KeepAliveTime, Unit, WorkQueue, Executors.defaultthreadfactory (), Defaulthan Dler);} Parameter interpretation: Corepoolsize, the number of core threads in the thread pool, by default, even if the core thread does not have a task to execute it also exists, we fixed a certain number of core threads and it survived this avoids the overhead of CPU creation and destroying threads in general. If we set the Allowcorethreadtimeout property of Threadpoolexecutor to True, then the idle core thread will have a timeout policy, which is set by KeepAliveTime. That is, the thread will be terminated if the core thread does not respond within the keepalivetime time.    Allowcorethreadtimeout defaults to False and the core thread does not have a time-out. Maximumpoolsize, the maximum number of threads in a thread pool, and other tasks may be blocked when the number of tasks exceeds the maximum number of threads. Maximum number of threads = core thread + non-core thread.    Non-core threads are created only when the core thread is not sufficient and the thread pool is free, and non-core threads are destroyed after the task is completed. KeepAliveTime, the non-core thread's timeout period, when execution time exceeds this time, non-core threads will be recycled.    This property also works on the core thread when Allowcorethreadtimeout is set to true. Unit, enumeration time units, TimeunIt WorkQueue, the queue of tasks in the thread pool, the runnable that we submit to the thread pools are stored on this object. The allocation of the thread pool follows the rule that when the number of core threads in the thread pool does not reach the maximum number of threads, a core thread is started to perform the task, and if the number of core threads in the thread pool reaches the maximum number of threads, then the task is inserted into the task queue and queued for execution if the task queue is full but the line If the number of threads in the process pool does not reach the total number of thread limits, a non-core thread is started to handle the task, and if the number of threads in the previous step reaches the limit, the thread pool refuses to perform the task. And Threadpoolexecutor calls Rejectedtionhandler's Rejectedexecution method to notify the caller.

The four thread pools are available through executors:

    1. Newcachedthreadpool: Create a cacheable thread pool, which is an unlimited thread pool, where all the threads created are non-core threads, if the thread pool length exceeds the processing needs, the time-out is set to 60s, if there is no task, the idle thread is recycled, and if there is no recyclable, The new thread. Used to perform some short-lived asynchronous tasks
public static ExecutorService new CachedThreadPool(){    return new ThreadPoolExecutor(        0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS,        new SynchronousQueue<Runnable>()    );}ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
    1. Newfixedthreadpool: Creates a thread pool that controls the maximum number of concurrent threads, and the excess threads wait in the queue. The number of pool threads is fixed and the created thread will persist. It does not have a timeout mechanism and waits for the queue to be infinite, so the fixedthreadpool is mostly for regular concurrent threads that are stable and fixed, and more for servers.
public static ExecutorService newFixedThreadPool(int nThreads){    return new ThreadPoolExecutor(        nThreads, nThreads, 0L, TimeUnit.MILLISECONDS,        new LinkedBlockingQueue<Runnable>()         );}//创建线程池ExecutorService mExecutor = Executors.newFixedThreadPool(5);//参数即核心线程数
    1. Newscheduledthreadpool Create a fixed-line pool, in fact, he put the advantages of the above two thread pool all together into a piece, he has a certain number of core threads, and unlimited capacity of non-core threads, the difference is that the non-core thread timeout is set to 0 seconds, that is, once idle, immediately recycle, Support timed and recurring task execution.
public static ScheduledThreadPool newScheduledThreadPool(int corePoolSize){    return new ScheduledThreadPoolExecutor(corePoolSize);}public ScheduledThreadPoolExecutor(int corePoolSize){    super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,          new DelayedWorkQueue());}ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(10);//核心线程数
    1. Newsinglethreadexecutor creates a single threaded thread pool with only one core thread, and it only uses a unique worker thread to perform the task, allowing the caller to ignore thread synchronization issues.
public static ExecutorService newSingleThreadExecutor(){    return new FinalizableDelegatedExecutorService(        new ThreadPoolExecutor(        1, 1, 0L, TimeUnit.MILLISECONDS,         new LinkedBlockingQueue<Runnable>()));}ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();

Thread Pool General Usage

    shutDown(),关闭线程池,需要执行完已提交的任务;    shutDownNow(),关闭线程池,并尝试结束已提交的任务;    allowCoreThreadTimeOut(boolen),允许核心线程闲置超时回收;    execute(),提交任务无返回值;    submit(),提交任务有返回值;

Newcachedthreadpool cache thread pool, if the threads are out of the flexible recycling, if not enough to create
Newfixedthreadpool the thread pool, you can set the maximum number of threads, and the exceeded task waits in the queue.
Newscheduledthreadpool is also a fixed-line pool that supports timed and recurring tasks.
Newsinglethreadexecutor a single threaded thread pool, tasks are slowly waiting to be executed in the queue according to the order of accession.

In addition to these, the role of threading in Android is Asynctask, Handlerthread, Intentservice. They are essentially composed of handler+thread.

Asynctask, which encapsulates the thread pool and handler, is primarily for our convenience of updating the UI in a child thread.
Handlerthread, which is a thread with Message Queuing, makes it easy for us to handle different transactions in a child thread.
Intentservice, we can consider it as an upgraded version of Handlerthread, which is a service with higher priority.

Reference
http://blog.csdn.net/weixin_36244867/article/details/72832632
http://blog.csdn.net/linchunquan/article/details/22382487
http://www.hchstudio.cn/2017/04/01/FutureTask%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/
Http://www.cnblogs.com/wenjiang/archive/2012/09/02/2668089.html



Bush LUN
Links: http://www.jianshu.com/p/d79dab197d5a
Source: Pinterest
Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.

Android Threads and thread pools

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.