Thread
By calling the START () method of the thread class to start a thread, the thread is in the ready (runable) state, but it is not running at this time. It requires a CPU time slice. Once the CPU time slice is obtained, the run () method is executed. The run () method is called the thread body. It contains the content of the thread to be executed. The run () method ends and ends.
Thread status conversion
1. New: A New thread object is created.
2. runnable: After a thread object is created, other threads (such as the main thread) Call the START () method of the object. The thread in this status is located in the runable thread pool, waiting to be selected by the thread scheduling to obtain the CPU usage right.
3. Running: the runnable thread obtains the CPU time slice and executes the program code.
4. Blocking: the thread gives up the CPU usage for some reason, that is, it gives up the CPU timeslice and stops running temporarily. It is not until the thread enters the runnable state that the CPU timeslice is re-obtained to the running state. Blocking is divided into three types:
- Wait for blocking: The Running thread executes the O. Wait () method, and the JVM puts the thread into the waiting queue.
- Synchronization congestion: When a running thread obtains the synchronization lock of an object, if the synchronization lock is occupied by another thread, the JVM puts the thread into the lock pool.
- Other blocking: The Running thread executes the thread. sleep (long MS) or T. when the join () method or an I/O request is sent, JVM sets this thread to blocking. When the sleep () status times out, the join () waits for the thread to terminate or times out, or the I/O processing is completed, the thread is re-transferred to the runnable status.
5. Dead: the execution of the run () and main () Methods ends, or the run () method exits due to exceptions. The dead thread cannot be re-generated.
Timer
There are two timer commonly used on the Android platform:
- Java Timer
- Alarmmanager for Android
Timer
The timer class of Java can be used to plan tasks that require cyclic execution. The problem with timer is that it needs to use wakelock to keep the CPU awake, which will consume a lot of cell phone power, greatly reduce the standby time of the mobile phone. This method cannot meet our needs.
Alarmmanager
Alarmmanager is a module encapsulated by the Android system for managing RTC. RTC (real time clock) is an independent hardware clock that can run normally during CPU sleep and when the preset time arrives, wake up the CPU by interrupting it. This means that if we use alarmmanager to regularly execute tasks, the CPU can sleep normally, and only a short period of time can be woke up when the task needs to be run.