Reference Source: Guo Lin. First line of code (Android) Https://www.gitbook.com/book/hzj163/android-thread/details I. Process
A process is an instance of a running program, the basic unit of resource allocation and protection in the operating system
Two. Threads
Threads are entities that can execute concurrently in a process, are part of a process, and are the basic unit of processor Dispatch and dispatch, and a process can contain multiple threads that share the memory space and resources acquired by the process, and can work together to accomplish a task, increasing the speed and efficiency of completing tasks
Three. Create thread 1. Inherit the thread class
Create
Class Testthread extends thread{ @Override public void Run () {/ * code to run in multithreaded */ }}
Start
Testthread mythread=new Testthread;mythread.start ();//Call the Start method inherited from Thread
2. Implement the Runnable interface
The way you use inheritance is a bit high, and you can inherit only one parent class, and the interface implements multiple. So we can use the interface way.
Testthread mytestthread=new testthread ();//Generate a Runnable interface implementation object thread Ti=new thread (mytestthread);// Pass this object as a constructor parameter to the thread object Ti.start ();
3. Using Anonymous Classes
If you don't want to bother creating a new class, you can use the anonymous class method
New Thread (New Runnable () {@Overridepublic void Run () {//Processing specific Logic }}). Start ();
Four. Thread Pool//todo
In object-oriented programming, creating and destroying objects is time-consuming, because creating an object takes memory resources or more resources. More so in Java, virtual machines will attempt to track each object so that it can be garbage collected after the object is destroyed. So one way to improve the efficiency of the service process is to minimize the number of objects created and destroyed, especially the resource-intensive object creation and destruction. How to use the existing object to serve is a key problem that needs to be solved, in fact, this is the reason that some "pooling resources" technology produces.
Using the thread pool reduces the number of times a thread is created and destroyed, and each worker thread can be reused to perform multiple tasks. And according to the ability of the system, the number of threads in the thread pool can be adjusted to prevent the server from consuming too much memory (approximately 1MB of memory per thread, the more threads open, the more memory is consumed and the last crashes).
Five. Thread synchronization (thread safe)
With multi-threaded access, a locking mechanism is used, and when one thread accesses one of the classes ' data, it is protected, and other threads cannot access it until the thread has finished reading and the other threads are available. Ensure that data is accessed at most one thread at any time to ensure the integrity of the data.
In Java, thread synchronization is guaranteed through the Synchronized keyword.
Every object in Java has an internal lock, and if a method is declared with the Synchronized keyword, the lock on the object will protect the entire method.
Public synchronized void Method () { //method body}
Thread not secure
Does not provide data access protection, it is possible for multiple threads to change data sequentially causing the resulting data to be dirty data
Six. The main thread of the UI in Android
When the app starts, the system creates a main thread (main thread). This main thread is responsible for distributing events (including drawing events) to the UI component, and in this main thread, your app interacts with the Android UI component. So the main thread is also called the UI thread.
If all the work is done on the UI thread, doing more time-consuming work such as accessing the network or querying the database will block the UI thread, causing the event to stop distributing (including drawing events). For the user, the app looks like it's stuck, and worse, if the UI thread blocked for too long (about 5 seconds), the user sees a dialog box for the ANR (application not responding). All this part of the work is finally done with an asynchronous thread.
Andoid UI Toolkit is not thread-safe, so you cannot manipulate UI components from a non-UI thread. You have to put all the UI actions in the UI thread, and all view and ViewGroup can only run in the UI main thread. If view or ViewGroup is running in the secondary thread, it will throw "only the original Threadthat created a view hierarchy can touch it views".
So Android's single-threaded model has two principles:
1. Do not block the UI thread.
2. Do not access the Android UI Toolkit (mainly the components in these two packages: Android.widget and Android.view) outside the UI thread.
Seven. Communication between threads and threads: Android messaging mechanism
However, the UI needs to be changed depending on the execution of the thread (for example, when the UI content is loaded after the network is connected), because the secondary thread cannot modify the UI directly, and it tells the UI in the main thread when to modify it through a message mechanism.
The messaging mechanism in Android consists of the following sections:
1. Message
A message is an information that is passed between threads, and it can carry a small number of messages inside to exchange data between different threading.
The Message uses the What field to carry the string type, uses the Arg1 and Arg2 fields to carry some integer data, and uses the Obj field to carry a single Object object.
2. Handler
Handler, as the name implies, is the meaning of the processor, which is primarily used to send and process messages. Sending a message is typically using the handler SendMessage () method, and the emitted message is processed in a series of ways and is eventually passed to the handler Handlemessage () method.
How to Eat
You first need to create a Handler object in the main thread and override the Handlemessage () method.
Then, when UI action is required in a child thread, a message object is created, which is sent through Handler.
The message is then added to the MessageQueue queue for processing, and Looper tries to remove the pending message from MessageQueue and finally distributes it back to the Handlemessage () method of handler.
Since Handler is created in the main thread, the code in the Handlemessage () method will also run in the main thread, so we can do the UI operation safely here.
In the main thread, create the Handler object, overriding the Handlemessage method private Handler Handler = new Handler () { @Override public Void Handlemessage (Message msg) { switch (msg.what) {case update_text:// can be used here for UI action text.settext ("Nice To meet "); break; Default: Break ; } } In a child thread, new thread (new Runnable () {@Overridepublic void run () { Message message = new Message ();//Create a Message object Message.what = Update_text; Handler.sendmessage (message); send the Message object out } }). Start ();
3. MessageQueue
MessageQueue is the meaning of Message Queuing, which is primarily used to store all messages sent through Handler. This part of the message will remain in the message queue and wait for it to be processed. There will only be one MessageQueue object in each thread.
4. Looper
Looper is the steward of MessageQueue in each thread, and after calling the Looper loop () method, it enters an infinite loop, and whenever a message is found in MessageQueue, it is removed and passed to the handler The Handlemessage () method. There will only be one Looper object in each thread.
Eight. Multi-threaded asynchronous Async method A on method B is called, no pipe B is run, a continues to run. Asynctask with Asynctask, you can easily switch from a child thread to the main thread, even if you do not understand the asynchronous message processing mechanism at all. Of course, asynctask behind the implementation of the principle is based on asynchronous message processing mechanism, but Android helped us to do a good package.
Basic usage
Asynctask is an abstract class, so if we want to use it, we'll have to create a subclass to inherit it. In inheritance we can specify three generic parameters for the Asynctask class, and these three parameters are used as follows.
1. Params
Initialize parameter types
2. Progress
Progress parameter type
3. Result
The return value parameter type.
Therefore, one of the simplest custom asynctask can be written as follows:
Class Downloadtask extends Asynctask<void, Integer, boolean> { ...}
A chestnut
Class Downloadtask extends Asynctask<void, Integer, boolean> {//This method is called before the background task begins execution, and is used for initialization of some interfaces @Override protected void OnPreExecute () {progressdialog.show ();//Show Progress Dialog}/* All code in this method will run in a sub-thread, we should be here to handle all the time-consuming Works Once the task is completed, the result of the task execution can be returned by the return statement, and if Asynctask's third generic parameter specifies Void, the task execution result is not returned. Note that the UI action is not allowed in this method, and if you need to update the UI elements, such as feedback on the progress of the current task, you can call Publishprogress (Progress ...). method to complete. */@Override protected Boolean doinbackground (Void ... params) {//try {while (true) { int downloadpercent = Dodownload (); This is a fictional method of publishprogress (downloadpercent); if (Downloadpercent >=) {break; }}} catch (Exception e) {return false; } return true; }/* When Publishprogress (Progress ...) is called in a background task Method, the method is called quickly, and the parameters that are carried in the method are passed in the background task. The UI can be manipulated in this method, and the interface elements can be updated accordingly using the values in the parameters. */@Override protected void onProgressupdate (Integer ... values) {//update download Progress progressdialog.setmessage here ("downloaded" + values[0] + "%"); */* This method will be called quickly when the background task is completed and returned through a return statement. The returned data is passed as a parameter to this method, and the returned data can be used to perform some UI actions, such as reminding the result of the task execution, and closing the Progress Bar dialog box. */@Override protected void OnPostExecute (Boolean result) {Progressdialog.dismiss ();//Close Progress Dialog//prompt for download results here if (result) {Toast.maketext (context, "Download succeeded", Toast.length_short). Show ( ); } else {Toast.maketext (context, "Download failed", Toast.length_short). Show (); } }}
Android Thread notes