Android Development Notes: Handler Runnable and Thread differences

Source: Internet
Author: User

In java, You can implement multithreading in two ways. One is to inherit the Thread class, the other is to implement the Runnable interface, and the Thread class is defined in the java. lang package. As long as a class inherits the Thread class and overwrites the run () method in this class, it can implement multi-threaded operations. However, a class can only inherit one parent class, which is the limitation of this method.
The following is an example: Copy codeThe Code is as follows: package org. thread. demo;
Class MyThread extends Thread {
Private String name;
Public MyThread (String name ){
Super ();
This. name = name;
}
Public void run (){
For (int I = 0; I <10; I ++ ){
System. out. println ("thread start:" + this. name + ", I =" + I );
}
}
}
Package org. thread. demo;
Public class ThreadDemo01 {
Public static void main (String [] args ){
MyThread mt1 = new MyThread ("thread ");
MyThread mt2 = new MyThread ("thread B ");
Mt1.run ();
Mt2.run ();
}
}

However, the results are regular at this time. The first object is executed first, and then the second object is executed without running each other. In the JDK documentation, we can find that once the start () method is called, The run () method is found through JVM. Start the thread by starting start:Copy codeThe Code is as follows: package org. thread. demo;
Public class ThreadDemo01 {
Public static void main (String [] args ){
MyThread mt1 = new MyThread ("thread ");
MyThread mt2 = new MyThread ("thread B ");
Mt1.start ();
Mt2.start ();
}
};

In this way, the program can run interactively. So why do we have to use the start (); Method to start multithreading?
In the installation environment of JDK, src.zip is the full java source program. By finding the definition of the start () method in Thread, we can find that private native void start0 () is used in this method (); the native keyword indicates that the underlying functions of the operating system can be called, so this technology becomes JNI technology (java Native Interface)
Runnable interface
In actual development, a multi-threaded operation rarely uses the Thread class, but is completed through the Runnable interface.Copy codeThe Code is as follows: public interface Runnable {
Public void run ();
}
Example:
Package org. runnable. demo;
Class MyThread implements Runnable {
Private String name;
Public MyThread (String name ){
This. name = name;
}
Public void run (){
For (int I = 0; I <100; I ++ ){
System. out. println ("thread start:" + this. name + ", I =" + I );
}
}
};

However, the start () method is not available in the subclass defined by Runnable, and is available only in the Thread class. Observe the Thread class, there is a constructor: public Thread (Runnable targer) This constructor accepts Runnable subclass instances, that is, you can use the Thread class to start the multi-Thread implemented by Runnable. (Start () can coordinate system resources ):Copy codeThe Code is as follows: package org. runnable. demo;
Import org. runnable. demo. MyThread;
Public class ThreadDemo01 {
Public static void main (String [] args ){
MyThread mt1 = new MyThread ("thread ");
MyThread mt2 = new MyThread ("thread B ");
New Thread (mt1). start ();
New Thread (mt2). start ();
}
}

Differences and links between the two implementation methods:
In program development, as long as it is multi-Thread, it will always be dominated by implementing the Runnable interface, because implementing the Runnable interface has the following advantages over inheriting the Thread class:
• Avoid the limitations of point inheritance. A class can inherit multiple interfaces.
• Suitable for Resource Sharing
Taking the ticket selling program as an example, the Thread class is used to complete:Copy codeThe Code is as follows: package org. demo. dff;
Class MyThread extends Thread {
Private int ticket = 10;
Public void run (){
For (int I = 0; I <20; I ++ ){
If (this. ticket> 0 ){
System. out. println ("ticket selling: ticket" + this. ticket --);
}
}
}
};

The following uses three thread objects to sell tickets at the same time:Copy codeThe Code is as follows: package org. demo. dff;
Public class ThreadTicket {
Public static void main (String [] args ){
MyThread mt1 = new MyThread ();
MyThread mt2 = new MyThread ();
MyThread mt3 = new MyThread ();
Mt1.start (); // each thread sells 10 tickets, with a total of 30 tickets.
Mt2.start (); // but there are only 10 tickets, each thread sells its own tickets
Mt3.start (); // resource sharing failed
}
}

If Runnable is used, resources can be shared. The following is an example:Copy codeThe Code is as follows: package org. demo. runnable;
Class MyThread implements Runnable {
Private int ticket = 10;
Public void run (){
For (int I = 0; I <20; I ++ ){
If (this. ticket> 0 ){
System. out. println ("ticket selling: ticket" + this. ticket --);
}
}
}
}
Package org. demo. runnable;
Public class RunnableTicket {
Public static void main (String [] args ){
MyThread mt = new MyThread ();
New Thread (mt). start (); // same mt, but not in Thread.
New Thread (mt). start (); // an exception occurs when the object mt is instantiated.
New Thread (mt). start ();
}
};

Although there are currently three threads in the program, a total of 10 tickets are sold. That is to say, using Runnable to implement multithreading can achieve resource sharing.
The connection between the Runnable interface and Thread:
Public class Thread extends Object implements Runnable
The Thread class is also a subclass of the Runnable interface.
Second:
Thread is the resource provided by the system. With Thread, you have the right to get the executable time slice from the CPU. Thread does not know your program, and does not know such a class as test, as there are tens of millions of programmers, each person has different names and wants to do different things, so Thread only knows one! That is Runnable. Thread knows Runnable and knows that Runnable has a run method. Once the start method of Thread is called, the run in the Runnable method will be automatically run by Thread. Therefore, when we inherit our class (the implementation interface should be called here) from Runnable, our program belongs to the Runnable type. It is a subclass of Runnable, but people know your father and you. Thread can be used no matter what internal conditions you have. It only takes you to have the run () method, and it calls start to let you run the run Command. So we can write something in the run command, this allows the system to run the code we want to do. Is it easy to understand? So the step to run the thread is: 1. Generate our own class Object 2. Obtain Thread 3 from the system. Let Threa call our class object, let it start up code: test a = new test (); Thread thread = new Thread (a); // Thread requires a parameter, it is the thread class you compiled, so that he knows your thread and is eligible to apply for a CPU time slice thread from the system. start (); you can simply write: new Thread (). start ();
Third:
Runnable is not necessarily a new thread. For example, the following call method is run in the main UI thread:Copy codeThe Code is as follows: Handler mHandler = new Handler ();
MHandler. post (new Runnable (){
@ Override public void run ()
{// TODO Auto-generated method stub
}
});

The official explanation of this method is as follows. Note the following: "The runnable will be run on the user interface thread ."
Boolean android. view. View. post (Runnable action)
Causes the Runnable to be added to the message queue. The runnable will be run on the user interface thread.
Parameters:
Action The Runnable that will be executed.
Returns:
Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting.
We can call the post method of handler to pass the Runnable object (generally a subclass of Runnable) to the past. handler will call the Runnable Run method in logoff for execution.
Runnable is an interface rather than a thread. Generally, a thread implements Runnable. Therefore, if we use an anonymous internal class to run in the UI main thread, if we use the Thread class that implements this Runnable interface, it runs in the corresponding thread.
Specifically, the function works as follows:
View. post (Runnable) method. In the post (Runnable action) method, View gets the Handler of the current thread (that is, the UI thread), and then post the action object to the Handler. In Handler, it packs the passed action object into a Message (the callback of the Message is action), and then inputs it into the Message loop of the UI thread. When Handler processes the Message again, a branch (uninterpreted) is set for it and the runnable run method is called directly. At this time, it has been routed to the UI thread, so we can update the UI without any concerns.
As shown in the preceding code, the Message callback is a Runnable anonymous internal class.
In this case, because it is not used in a new thread, do not make complicated computing logic.

Fourth: in multi-Thread programming, Handler, Thread, and Runnable classes are often used. Are you aware of the relationship between them?
First, it indicates that the minimum unit of CPU allocation for Android is Thread, and Handler is generally created in a Thread. Therefore, Handler and Thread are bound to each other and correspond to each other one by one.
Runnable is an interface and Thread is a subclass of Runnable. Therefore, both of them are considered a process.
As the name implies, HandlerThread is a thread that can process message loops. It is a thread with logoff and can process message loops.
Instead of binding a Handler to a thread, it is better to say that Handler is one-to-one correspondence with logoff.
It should be noted that in the UI thread (main thread:Copy codeThe Code is as follows: mHandler = new Handler ();
MHandler. post (new Runnable (){
Void run (){
// Execute the code...
}
});
This thread is actually running within the UI thread, and there is no new thread.
The common method for creating a thread is:
Thread thread = new Thread ();
Thread. start ();
HandlerThread thread = new HandlerThread ("string ");
Thread. start ();

Fifth, when writing the Java Runnable interface, we need to constantly learn the relevant code. Next we will look at how Hyun can use the relevant code. The Runnable interface has only one method run (). We declare our class to implement the Runnable interface and provide this method. By writing our thread code into it, this part of the task is completed.
However, the Runnable interface does not support any threads. We must also create an instance of the Thread class, which is achieved through the Thread class constructor public Thread (Runnable target. The following is an example:Copy codeThe Code is as follows: public class MyThread implements Runnable
{
Int count = 1, number;
Public MyThread (int num)
{
Numnumber = num;
System. out. println ("creation thread" + number );
}
Public void run ()
{
While (true)
{
System. out. println
("Thread" + number + ": count" + count );
If (++ count = 6) return;
}
}
Public static void main (String args [])
{
For (int I = 0; I <5;
I ++) new Thread (new MyThread (I + 1). start ();
}
}

Strictly speaking, creating a Thread subclass instance is also feasible, but it must be noted that this subclass must not overwrite the Thread class's run method, otherwise, the thread will execute the run method of the subclass, rather than the run method of the class we use to implement the Runnable interface. You may try this out.
Using the Java Runnable interface to implement multithreading enables us to include all the code in a class and facilitate encapsulation. Its disadvantage is that we can only use one set of code, if you want to create multiple threads and run different code generations for each thread, you must create additional classes, in most cases, it may be better to use multiple classes to inherit the Thread.

Related Article

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.