Android Multithreading Technology Application _android

Source: Internet
Author: User
Tags inheritance stub thread class touch
Multi-threaded case-timer
In this case, after the screen starts, enter the interface as shown in the figure.
There is a text box on the screen to show the elapsed time, in addition to a "Stop Timer" button. The use case diagram of the case is shown in the figure.

To be able to "display in real time" on the screen, a single-threaded programming can not be achieved, it must be multithreaded to achieve, even if some computer languages can be encapsulated in the class to achieve this function, but the essence of these encapsulated class is to encapsulate a thread.
To sum up, complete this case to use the knowledge and technology as follows:
1 The concept of process and thread;
2 The thread in Java, the way in which threads are created in Java;
3 Android threads, including: message, Handler, Looper, and Handlerthread concepts.
What is a thread? Prior to the advent of the Windows operating system, the operating system on personal computers was a single task, with multitasking and time-sharing design only on large computers. The advent of Windows and Linux operating systems has brought to the personal computer system the advantages that were originally only in mainframe computers.
Process Concepts
The operating system that can normally execute multiple programs at the same time has the concept of a process. A process is an executing program, and each process has its own separate piece of memory space, a set of system resources. In the concept of a process, the internal data and state of each process are completely independent. Under the Windows operating system we can view processes through the 〈ctrl+alt+del〉 key combination, which is viewed through the PS command under UNIX and Linux operating systems. Open the process that Windows is currently running, as shown in the figure.

In the Windows operating system, a process is an EXE or DLL program that is independent of each other and can communicate with each other, and there are many applications in the Android operating system for communication between processes.
Threading Concepts
Multithreading means that you can run several different threads at the same time in a single program to perform different tasks. Multithreading means that a multiple-line statement of a program can appear to run at the same time almost simultaneously.
A thread is similar to a process, a piece of code that completes a particular function, and is the flow control in a single sequence in a program. Unlike processes, however, multiple threads of the same class share a single memory space and a set of system resources, so the system switches between threads, resource consumption is much smaller than the process, and because of this, threads are also referred to as lightweight processes. You can include multiple threads in a process. The diagram shows the relationship between the timer program process and the thread, which is responsible for managing the child threads, that is, the start, suspend, and stop operations of the child threads.

Threads in Java
The Java thread class is the Java.lang.Thread class. When an object of the thread class is generated, a new thread is generated. Each thread in Java completes its operation through the method run () of a particular thread object, and method run () is called the thread body.
Here are some common ways to build thread classes:
Public Thread ()
Public Thread (Runnable target)
Public Thread (Runnable target, String name)
Public Thread (String name)
The parameter target is an instance of the implementation of the Runnable interface, which is used to implement the run () method of the thread body. Destination target can be null, representing the execution of threads by itself instance. The name parameter specifies the thread name, but no constructor is specified, and the thread is named by the JVM, for example, the JVM is designated as thread-1, Thread-2, and so on.
1, Java implementation of the thread body mode 1
In Java, there are two ways to implement line Cheng: One is to inherit thread class thread and the other is to implement Interface runnable. Let's take a look at the inheritance thread class thread method first.
In the 1th way, it inherits thread class thread and overrides the method run (), which, when initializing the class instance, can be null, representing the execution of the thread body by this instance. Because Java only supports single inheritance, classes defined in this way can no longer inherit other parent classes, such as the code listings as shown:
Copy Code code as follows:

Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
public class Textthread extends Thread {
Boolean flag = true;
int timer = 0;
@Override
public void Run () {
Super.run ();
try {
while (flag) {
This.currentthread (). Sleep (1000);
timer++;
System.out.print (timer);
}
catch (Interruptedexception e) {
E.printstacktrace ();
}
}
public static void Main (string[] args) {
Textthread thread = new Textthread ();
Thread.Start ();
System.out.print ("Start timer ...");
BufferedReader reader = new BufferedReader (new InputStreamReader (system.in));
try {
String line = Reader.readline ();
if (Line.equalsignorecase ("1")) {
Thread.stop ();
Thread.flag = false;
}
catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}

In the main main method, a child thread is created through the new Textthread (), and the child thread is started by the Thread.Start () method, the main main method is in the thread of the main thread, and the main thread is responsible for managing the other child threads. The relationship between this example process, main thread, and child threads is shown in the figure.
The run () method is invoked after the child thread starts, and run () is a thread body, and we are writing code here to handle things in child threads. This case of the neutron thread to do is: hibernate 1s, timer plus 1, and then repeatedly executed. Thread.CurrentThread () sleep (1000) is dormant 1s.
To be able to stop the thread, we added an identity to the main thread by entering a character in the console
"1" To change the identity t1.isrunning = False to end this thread.

Attention
In fact, there is a stop () method in the thread that can also stop the thread, but since this method produces a thread deadlock problem, it has been abolished in the new JDK, and its alternative solution is to increase the identity, which is the scenario we use in this example.
   Many people find threading difficult to understand, and there are two main problems
Thread hibernate, can the program run faster if the thread is already dormant?
Thread bodies are generally dead loops, and now that the thread is dead, the program should die and there will be no response.
   1. About Thread hibernation issues
Thread hibernation problem readers, in fact, are still using a single-threaded thinking mode to consider the problem, in most cases, our PC is a single CPU, a point in time can only have one thread to run. Multithreading means that multiple threads perform alternately, as if they were running at the same time. Therefore, the current thread of hibernation can hand over CPU control, let other threads have the opportunity to run, the more than a few threads between the efficiency is the highest, it is like we drive across the intersection, only me and so on, let you first, you wait for him first, to ensure the highest efficiency, otherwise it will cause the traffic system crashes, The same is true for threading situations. Therefore, the hibernation of thread threads is the most efficient way to run a program.
   2. About Thread-Body dead loop problem
In a single thread if it is a dead loop, the program should die, there is no response, but the multithreaded centerline Cheng (Run method) in the dead loop, you can ensure that the thread has been running, if not the loop, then run once stopped. In the example above, the thread body runs a dead loop, which ensures that the threads run all the time, hibernate 1s each time, and then wake up and then output the information to the console. Therefore, the thread body dead loop is the prerequisite to ensure that the child threads keep running. Because it is a child thread that does not block the main thread, it does not feel that the program is dead. However, it should be noted that sometimes we do execute the thread body once, and there is no need to loop.
Start the thread after the program is run, and the thread starts to calculate the elapsed time, outputting the results to the console every 1s. When 1 characters are entered, the thread stops and the program terminates. As shown in the figure.

implementing threaded Body Mode in Java 2
This article describes the inheritance thread approach to implement the threaded body, and here's another way to provide a class that implements the interface runnable as the target object of a thread with two construction methods with runnable target parameters:
Thread (Runnable target);
Thread (Runnable target, String name).
The target is the thread target object, which is a class that implements the runnable, passing the target object (the Runnable class) to the thread instance when constructing the thread class, providing the thread-body run () method with the target object (the class that implements Runnable). The class that implements the interface runnable can still inherit other parent classes.
See the code listing, which is a Java AWT form application.
Copy Code code as follows:

Import java.awt.*;
Import java.awt.event.ActionEvent;
Import Java.awt.event.ActionListener;
public class TextThread2 extends Frame implements Runnable, ActionListener {
Public label label;
Public button button;
Public Thread Clockthread;
public Boolean isrunning;
public int timer = 0;
Public TextThread2 () {
button = New button ("Stop Timer");
Label = new label ("calculator start");
Button.addactionlistener (this);
SetLayout (New BorderLayout ());
Add (Button, "North");
Add (Label, "Center");
SetSize (320, 480);
SetVisible (TRUE);
TextThread2 textThread2 = new TextThread2 ();
Clockthread = new Thread (this);
Clockthread.start ();
IsRunning = true;
}
@Override
public void actionperformed (ActionEvent e) {
IsRunning = false;
}
@Override
public void Run () {
TODO auto-generated Method Stub
try {
while (isrunning) {
Thread.CurrentThread (). Sleep (1000);
timer++;
Label.settext ("dead" + timer);
}
catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
/**
* @param args
*/
public static void Main (string[] args) {
TODO auto-generated Method Stub
TextThread2 textThread2 = new TextThread2 ();
}
}

The Java AWT knowledge is not introduced here, interested readers can look at the relevant books themselves. In this case, the way to build an AWT form is to inherit the frame class. The 1th way-the inheritance way to implement line Cheng is not possible, because Java is a single inheritance, this class cannot inherit both frame and thread. A 2nd approach should be adopted--the implementation of Runnable interface mode. The Runnable interface also has a run () method that implements the threaded body method, and its code processing is the same as in the previous section. It should be noted that in the 2nd method, a thread member variable clockthread is created to create a threading object with the constructor new thread (this), where the construction method used by the creation thread is thread (Runnable target). This represents this instance, which is an implementation class that implements the Runnable interface.
The program runs as shown in the picture, when the screen starts to load, the thread starts the calculation time, the 1s updates the UI once, and stops timing when the "End Timer" button is clicked.

implementing threaded Body Mode in Java 3
Implementing threaded Body Mode 3 is a variant of thread-body mode 2, which essentially implements thread-body mode 2, but is often used in the 3rd way in Android application development. Here we look at the 3rd way of the timer code list.
Copy Code code as follows:

Import java.awt.*;
Import java.awt.event.ActionEvent;
Import Java.awt.event.ActionListener;
public class TextThread3 extends Frame implements ActionListener {
Private button button;
private Label label;
Private Thread Clockthread;
private int timer = 0;
Private Boolean isrunning = true;
Public TextThread3 () {
button = New button ("Stop timing");
Label = new Label ("Start of timer ...") ");
Button.addactionlistener (this);
SetLayout (New BorderLayout ());
Add (Button, "North");
Add (Label, "Center");
SetSize (320, 480);
SetVisible (TRUE);
Clockthread = new Thread (new Runnable () {
@Override
public void Run () {
while (isrunning) {
try {
Thread.CurrentThread (). Sleep (1000);
Timer + +;
Label.settext ("Gone:" +timer);
catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
});
Clockthread.start ();
IsRunning = true;
}
@Override
public void actionperformed (ActionEvent e) {
IsRunning = false;
}
/**
* @param args
*/
public static void Main (string[] args) {
TextThread3 thread3 = new TextThread3 ();
}
}

Compared with the 2nd approach, we found that the frame class no longer implements the Runnable interface, but instead defines an anonymous inner class that implements the Runnable interface when the thread class is instantiated:
Copy Code code as follows:

Clockthread = new Thread (new Runnable () {
@Override
public void Run () {
while (isrunning) {
try {
Thread.CurrentThread (). Sleep (1000);
Timer + +;
Label.settext ("Gone:" +timer);
catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
});

There are still a lot of Java multithreading content, such as thread priority, thread synchronization, and so on, because the content is not very close to the book, so no longer introduced, the other thread knowledge can refer to the Java aspects of the book. Next, let's introduce the threads in Android.
the threads in Android
Multithreading is widely used in Android platforms and requires multiple threads for UI updates, game development and time-consuming processing (network communications, etc.). The technology involved with Android threads is: Handler; message; MessageQueue; Looper; Handlerthread.
   problems and analysis in the application of Android thread
To introduce these concepts, we ported the timer case to the Android system, following the modified code listing in frame mode.
Copy Code code as follows:

Package com.example.testthread4;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.Message;
Import android.widget.*;
Import android.app.Activity;
Import Android.view.Menu;
Import Android.view.View;
Import Android.view.View.OnClickListener;
public class Mainactivity extends activity {
Private Button Mbutton;
Private TextView Mtextview;
Private Boolean isrunning = true;
Private Thread Mthread;
private int timer = 0;
Private Handler Handler;
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Mbutton = (Button) Findviewbyid (R.id.button1);
Mtextview = (TextView) Findviewbyid (R.ID.TEXTVIEW1);
Mbutton.setonclicklistener (New Onclicklistener () {
@Override
public void OnClick (View arg0) {
TODO auto-generated Method Stub
IsRunning = false;
}
});
/*handler = new Handler () {
@Override
public void Handlemessage (msg) {
Switch (msg.what) {
Case 0:
Mtextview.settext ("Gone:" + msg.obj);
}
}
};*/
Mthread = new Thread (new Runnable () {
@Override
public void Run () {
try {
while (isrunning) {
Thread.CurrentThread (). Sleep (1000);
timer++;
/*message message = new Message ();
Message.obj = timer;
Message.what = 0;
Handler.sendmessage (message);
Mtextview.settext ("Gone:" +timer);
}
catch (Interruptedexception e) {
E.printstacktrace ();
}
}
});
Mthread.start ();
}
}

There was an exception to the package run result, as shown in the figure.

We open the Logcat window, error log information as shown in the picture.

The exception information thrown by the system is "only the original thread" created a view hierarchy can touch its views ", the Update UI processing in Android must be updated by the thread that created it, not in other threads Update in. This is the reason for the above error.
Now to analyze the above case, there are two threads in the above program: a main thread and a child thread whose responsibilities are shown in the figure.
Because Labeltimer is a UI control that is created in the main thread, it is updated in a child thread, and the update operation is implemented in the Clockthread thread's Run () method, as follows:

Copy Code code as follows:

Mthread = new Thread (new Runnable () {
@Override
public void Run () {
try {
while (isrunning) {
Thread.CurrentThread (). Sleep (1000);
timer++;
/*message message = new Message ();
Message.obj = timer;
Message.what = 0;
Handler.sendmessage (message);
Mtextview.settext ("Gone:" +timer);
}
catch (Interruptedexception e) {
E.printstacktrace ();
}
}
});

Such processing violates the Android multithreaded programming rules, and the system throws an exception "only the original thread" created a view hierarchy can touch its views.
To solve this problem, it is necessary to identify the main thread and child thread responsibilities. The responsibility of the main thread is to create, display, and update UI controls, handle UI events, start child threads, stop child threads, and child threads to calculate elapsed time and to issue update UI messages to the main thread instead of directly updating the UI.
The responsibility of the main thread is to display UI controls, handle UI events, start child threads, stop child threads, and update the UI, which is the responsibility of the child thread to calculate elapsed time and to issue update UI messages to the main thread. But the new problem arises: how do child threads and main threads send messages and communicate?
In Android, threads have two objects-messages (message) and Message Queuing (MessageQueue) that enable communication between threads. Let's look at the revised code list below.
Copy Code code as follows:

Package com.example.testthread4;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.Message;
Import android.widget.*;
Import android.app.Activity;
Import Android.view.Menu;
Import Android.view.View;
Import Android.view.View.OnClickListener;
public class Mainactivity extends activity {
Private Button Mbutton;
Private TextView Mtextview;
Private Boolean isrunning = true;
Private Thread Mthread;
private int timer = 0;
Private Handler Handler;
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Mbutton = (Button) Findviewbyid (R.id.button1);
Mtextview = (TextView) Findviewbyid (R.ID.TEXTVIEW1);
Mbutton.setonclicklistener (New Onclicklistener () {
@Override
public void OnClick (View arg0) {
TODO auto-generated Method Stub
IsRunning = false;
}
});
Handler = new Handler () {
@Override
public void Handlemessage (msg) {
Switch (msg.what) {
Case 0:
Mtextview.settext ("Gone:" + msg.obj);
}
}
};
Mthread = new Thread (new Runnable () {
@Override
public void Run () {
try {
while (isrunning) {
Thread.CurrentThread (). Sleep (1000);
timer++;
Message message = new Message ();
Message.obj = timer;
Message.what = 0;
Handler.sendmessage (message);
}
catch (Interruptedexception e) {
E.printstacktrace ();
}
}
});
Mthread.start ();
}
}

Sometimes in order to make the Android code more compact, the creation and initiation of the thread is written in a single statement, as follows
Copy Code code as follows:

/*mthread = */new Thread (new Runnable () {
@Override
public void Run () {
try {
while (isrunning) {
Thread.CurrentThread (). Sleep (1000);
timer++;
Message message = new Message ();
Message.obj = timer;
Message.what = 0;
Handler.sendmessage (message);
}
catch (Interruptedexception e) {
E.printstacktrace ();
}
}
). Start ();

Run the emulator result as shown in Figure 8-1, start the timer immediately after loading the screen, or click the Stop Timer button to stop the timer.
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.