Android performance optimization-thread optimization

Android thread scheduling mechanism

Thread scheduling mechanism

  • Time-sharing scheduling model: All threads take turns to obtain CPU usage rights, and the CPU time occupied by each thread is evenly distributed
  • Preemptive scheduling model: Prioritize threads with high priority in the runnable pool to occupy the CPU, and randomly select a thread with the same priority

Android thread scheduling mechanism
Android’s thread scheduling mechanism is a preemptive scheduling model.
Thread priority (nice): By default, the priority of a newly created thread is the same as the parent thread by default.
Thread grouping: Android is also divided into foreground threads and background threads

Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND)

Android asynchronous mode

  • Thread: create a thread directly
  • AsyncTask: Provides a simple and convenient mechanism for fast switching between UI threads and worker threads. It is suitable for use scenarios that need to be started immediately but the life cycle of asynchronous execution is short ()
  • HanderThread: Set up a dedicated thread for certain callback methods or waiting for the execution of certain tasks, and provide thread task scheduling. (handerThread inherits the Thread+handler mechanism) Reference article: Teach you how to use HandlerThread
  • ThreadPool: Decompose tasks into different units and distribute them to different threads for simultaneous and concurrent processing.
  • IntentService: suitable for executing Service tasks triggered by UI, and can be fed back to UI through a certain mechanism when tasks are executed in the background (IntentService inherits from Service, and HandlerThread is used inside)
  • Loaders: Android system provides LoaderManager (AsyncTask used inside)

Android thread optimization

  • Thread specifies the thread name, grouping the threads for easy troubleshooting
  • Reasonably assign thread priority
  • Reuse threads with thread pool
  • Choose the right asynchronous method for the right scenario
  • Control the total number of threads of the entire application, and reuse threads for each module of the application
  • HandlerThread that is no longer used needs to exit
  • Do not directly use to create threads, thread pools should be used

Guess you like

Origin blog.csdn.net/yanwenyuan0304/article/details/106813636