Android multi-threaded interview

Android default program is only a process, a process which can contain multiple threads.

Multithreading - Introduction

Definition: multiple threads simultaneously, namely multiple tasks simultaneously.

note:

  1. In fact, the computer at any given time can only perform one task;
  2. Multithreading is only an illusion: just because the JVM fast scheduling resources to continue to take turns rotating thread execution, so it looks as if only perform multiple tasks at the same time.

A, Android thread Class and Action

1.1 By Application     

  • The main thread:

       Definitions: Android system will start a main thread automatically when the program starts

       Effect: treatment of the four components do interact with the user (e.g., UI, interface interaction related)

       Note: Because the user interface and interaction occur at any time, so the main thread must at all times maintain a high response speed, so the main thread does not allow for time-consuming operation, there would ANR

  • Child thread:

        Definition: A basic execution unit & CPU minimum unit program execution flow.

        Action: time consuming process operations, such as network requests, complex calculations, to reduce the time and memory program, when executed concurrently paid to improve the performance of concurrent operating systems.

        Sub-state of the thread as shown:

        

----------------------------------------------------------Thread-------------------------------------------------------------

2.2 According to the shape:

一、Thread

       1. Description: The  basic thread, you can do some simple operations, often with the use Handler.

       2, Thread main functions :

             RUN () : Code-threaded runtime execution

             start (): start the thread

             sleep (): thread sleep, into the blocked state, sleep method does not release the lock

             yield (): thread surrender CPU, but does not block but is reset to the ready state, will not release the lock

             interrupt (): interrupt thread, interrupted only pay attention to the blocked state thread

             setDaemon (): set and retrieve the guard whether thread

      3, Thread several state

            New State (new new) : This state is entered after the instantiation;

            Ready state (Runnable) : After the thread calls start () execution ready state to wait cpu, pay attention to this point does not mean only that you can run is already running;

            Operating state (Running) : cpu thread gets executed, and begin execution run () method;

            Blocked (Blocked) : thread into the blocked state due to various reasons: join (), sleep () , wait (), waiting for a trigger condition, waiting occupied by another thread lock;

            Death state (Dead) : the thread has finished running or abnormal exit, use isAlive () Gets the state.

      4, Android use in Thread

           1.1, inheritance Thread, rewrite run()method.

           1.2, to achieve Runnable, rewrite run()method to perform the task

           1.3, start the thread by Handler

      5, how to terminate the thread

            1.1, using boolean variable as marker

            1.2, usinginterrupt()

       Thread normal operation:  Interrupt threads instead of the end of the thread.

                    Thread blocked: throw an exception, this exception to the use of out of the loop.

            1.3, using the stop()method of terminating the thread

                 This is equivalent to forced shutdown in case of data loss more harm than good.

      6, security thread and thread synchronization

            1.1 What is a security thread?
             Simply put, security thread refers to multiple threads access the same code or data, resulting in confusion results and data.

            1.2, the solution method:

               (. 1) the synchronized  keyword, the same time to ensure that only one thread or block access to the method.

               (2) volatile special variable domain modified variables: the variable to tell the virtual machine may be updated at any time, are recalculated each time use, instead of using the value of the register.

               (3) ReentrantLock:  Use reentrant locks for thread synchronization.

               (4) ThreadLocal management variables: This variable is used for each thread will receive a copy of the variable, independent of each other copies.

---------------------------------------------------AsyncTask--------------------------------------------------------------

二、AsyncTask

       1, description: lightweight class asynchronous operation, easy to update the UI.

       2, the principle: encapsulates Handler and two thread pool.

            (1) thread pool THREAD_POOL_EXECUTOR: being true mission thread

            (2) thread pool SERIAL_EXECUTOR: Task Scheduler (allows multiple threads to tasks arranged in the order)

           (3) instantiates a WorkerRunnable object AsyncTask create mWorker and a FutureTask objects mFuture. FutureTask hair and is a class act as the role of Runnable. Next will use the serial line and worker threads to handle the actual task.

            (4) When you create an object passed as a parameter to WorkerRunnable FutureTask object, FutureTask on a mission run()when calls WorkerRunnable the call()method, so call()the method is carried out in the thread pool.

            (5) the main thread Handler:

  • After calling the call () method, call doInBackground and returns the result.
  • This process will catch the task was canceled out of the end of the set AsyncTask.
  • call()The last methodpostResult(result)。
  • Get the main thread Handler, communications worker thread and the main thread

   3, parameters, and core functions

   AsyncTask also provides four core methods:

  • protected void onPreExecute(): Before the main thread to perform asynchronous tasks calling preparatory work;
  • protected abstract Result doInBackground(Params... var1): Execution threads in the pool, used to perform asynchronous tasks. Params represents the asynchronous task input parameters, in this method by publishProgress to update task progress method, publishProgress in turn calls the onProgressUpdate way to achieve the main thread progress updates. This method returns Result to onPostExecute method.
  • protected void onProgressUpdate(Progress... values): In the main thread of execution, a background task execution schedule changes will call this method.
  • protected void onPostExecute(Result result): After the main thread execution, asynchronous tasks call, the Result parameter is doInBackground returned.

  4, AsyncTask Caution

  • AsyncTask object class must be created in the main thread load.
  • execute method must be called on the UI thread.
  • A AsyncTask object can only be performed once , that can only be called once the execute method, otherwise the report runtime exception.

  5, the advantages

  1. Simple and quick and easy to use.
  2. UI updates in a timely manner, the process control.

  6, shortcomings

    1, multiple asynchronous operation needs to be updated UI, it becomes troublesome.

---------------------------------------------------HandlerThread-----------------------------------------------------

三、HandlerThread

       1. Description: a used Looper, Handler thread.

       2, the principle

               (1) inherited Thread, is actually a Looper, Handler's threads.

               (2) inherited Thread, in the run()process by Looper.prepare()creating a message queue, Looper.loop()to process the message loop.

               (3) open when using HandlerThread, create Handler and HandlerThread binding of Looper, Handler message notification HandlerThread way to perform a specific task.

               (4) HandlerThread internal maintains a message queue, to avoid repeatedly create and destroy child thread to operate.

      3, example:

//创建HandlerThread实例,参数字符串定义新线程的名称。
HandlerThread mHandlerThread = new HandlerThread("check-message-coming");

//启动HandlerThread线程。
mHandlerThread.start(); 

//Handler与HandlerThread绑定
Handler mCheckMsgHandler = new Handler(mHandlerThread.getLooper()){
     @Override
     public void handleMessage(Message msg){
         // 进行耗时操作
     }
};

Note : To remember onPause()and onDestroy()pause and stop updating mHandlerThread to free up memory.

-------------------------------------------------- --- IntentService ---------------------------------------------- -------

Four, IntentService

      1, Description: IntentService encapsulates HandlerThread and a Handler, IntentService encapsulates HandlerThread and a Handler.

      2, the principle:

  • When you create a HandlerThread IntentService start, while Handler binding HandlerThread. Therefore messages sent by the Handler are performed in HandlerThread.
  • Then IntentService into the life cycle of onStartCommandrecall onStartwill be sent using the Intent object passed in the form of messages Handler.
  • Handler will be called after receiving the message onHandleIntentsuch an abstract method that we need to achieve their own processing logic. Finally processed stopSelf(msg.arg1);wait for all tasks to complete end IntentService;

-------------------------------------------------- ----- thread pool ------------------------------------------- ------------------

Fifth, the thread pool

     1, Principle:   

           Android in the thread pool concept comes in Java Executor, Executor is an interface for true thread is ThreadPoolExecutor. (ThreadPoolExecutor inherited AbstractExecutorService, AbstractExecutorService is ExecutorService implementation class, ExecutorService inherited the Executor interface).

      2, the advantages:

  1. Reuse threads in the pool, avoid frequent thread creation and destruction brought about by the memory overhead.
  2. Effective control of the maximum number of concurrent threads to avoid blocking phenomenon due to seize resources between threads caused.
  3. It can be a simple thread management, execution, and provide timing cycle execution time interval specified functions.

     3, the classification of the thread pool

      (. 1),  FixedThreadPool (Fixed: fixed, unchanging)    

      By Executors of newFixedThreadPoolcreation, through the creation of parameters can be seen and the following characteristics:

  • A fixed number of threads and threads are the core : core number of threads and the maximum number of threads are nThreads;
  • They are the core thread and will not be recovered quickly corresponding external request;
  • No time-out mechanism, the task queue is no size limit;
  • The new task using the core thread, if there are no free core thread is queued for execution.

      (2), CachedThreadPool (Cached: Cache)

       By Executors of newCachedThreadPoolcreation, it features:

  • A variable number of threads, only non-core thread, the maximum number of threads arbitrarily large : Incoming core number of threads parameter is 0, the maximum number of threads Integer.MAX_VALUE;
  • Use idle threads of execution when there is a new task, there is no idle thread creates a new thread to handle.
  • Each of the idle thread pool thread has a timeout mechanism, often for the 60s (parameters: 60L, TimeUnit.SECONDS), idle for more than 60s idle thread recovery.
  • For the implementation of a large number of less time-consuming task is stopped when all the threads will be idle for more than 60s, then it takes up little system resources.

     (. 3), ScheduledThreadPool (the Scheduled: predetermined, scheduled)

       By Executors of newScheduledThreadPoolcreation, it features:

  • The core thread fixed number, unlimited number of non-core thread ;
  • Non-core thread idle for over 10s will be recycled;
  • The main task of the timing for performing repetitive tasks and having a fixed period;
  • Four delay only inside a functional cycle performed repeatedly performed and

    (4), SingleThreadExecutor (single-threaded thread pool)
       by Executors of newSingleThreadExecutorcreation, features:

  • Only a core thread, all tasks are executed in sequence in the same thread.
  • All external tasks into one single thread, so the problem does not require synchronization processing thread.

     4, ThreadPoolExecutor Introduction

 public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             threadFactory, defaultHandler);
    }

 Parameter Description:   

  • corePoolSize: core number of threads the thread pool, the default core thread in the case would have been alive in the thread pool, even at idle.
  • maximumPoolSize: The maximum number of threads in the thread pool can hold, when the number of threads that number is reached, the follow-up of the new jobs will be blocked.
  • keepAliveTime: non-core thread timeout period, more than this time no task execution, non-core thread will be recovered.
  • unit: a unit of time specified keepAliveTime parameters.
  • workQueue: task queue thread pool.
  • threadFactory: thread factory, to provide the ability to create a new thread pool thread.
  • handler: type of the handler RejectedExecutionHandler . When a thread pool can not perform new tasks, it calls the handler's rejectedExecution(Runnable r, ThreadPoolExecutor e)method to throw an exception.

   5, ThreadPoolExecutor perform tasks generally follow the following rules:

(1) If the number of threads in the pool does not reach the number of kernel threads will directly start a kernel thread to perform the task.
(2) If the number of threads in the thread pool has reached or exceeded the number of kernel threads, then the task will be inserted into the task queue queued for execution.
(3) If the step 2 can not insert a new task, explain the task queue is full, if not reached the predetermined maximum number of threads, start a thread to perform non-core tasks.
(4) If the maximum value exceeds the specified number of threads in Step 3, then refused to use RejectedExecutionHandler task and the rejectedExecution(Runnable r, ThreadPoolExecutor e)method to inform the caller.

 

Original link: https://www.jianshu.com/p/56163a3beb4a   

https://cloud.tencent.com/developer/article/1424838

                 

 

Published 49 original articles · won praise 2 · Views 8592

Guess you like

Origin blog.csdn.net/yangjunjin/article/details/105025256