Android multithreading technology application

Source: Internet
Author: User

Multithreading case -- Timer
In this case, the interface is displayed after the screen is started.
There is a text box on the screen to show the elapsed time, and there is also a "stop timing" button. Use case diagram.

A single-threaded program cannot achieve the passage of time that can be "displayed in Real Time" on the screen. It must be a multi-threaded program, even if some computer languages can implement this function through encapsulated classes, these encapsulated classes encapsulate a thread in essence.
To sum up, the knowledge and technology used to complete this case are as follows:
1) concepts of processes and threads;
2) The thread creation method in Java;
3) threads in Android, including Message, Handler, logoff, and HandlerThread.
What is a thread? Before the appearance of a Windows operating system, the operating systems on personal computers were all single-task systems. They were only available on large computers for multi-task and time-based design. The emergence of Windows and Linux operating systems brings the advantages that were originally only available on large computers to the personal computer system.
Process Concept
Generally, an operating system that can execute multiple programs within the same time has the concept of a process. A process is an execution program, and each process has its own independent memory space and a group of system resources. In the process concept, the internal data and status of each process are completely independent. In Windows, you can run the Ctrl + Alt + Del key combination to view processes. In UNIX and Linux operating systems, you can run the PS command to view processes. Open the process currently running in Windows ,.

In a Windows operating system, a process is an exe or dll program. They are independent of each other and can communicate with each other. In the Android operating system, there are also many communication applications between processes.
Thread Concept
Multithreading means that multiple threads can be run simultaneously in a single program to execute different tasks. Multithreading means that multi-line statements of a program can run almost simultaneously at the same time.
Similar to a process, a thread is a piece of code that completes a specific function. It is a flow control of a single sequence in a program. Different from processes, multiple threads of the same type share a memory space and a group of system resources. Therefore, when the system switches between threads, the resource usage is much smaller than that of the process, for this reason, threads are also called Lightweight processes. A process can contain multiple threads. The figure shows the relationship between Timer Program processes and threads. The main thread is responsible for managing sub-threads, that is, operations such as starting, suspending, and stopping sub-threads.

Java threads
The Java Thread class is the java. lang. Thread class. After a Thread class object is generated, a new Thread is generated. In Java, each Thread completes its operations through the method run () of a specific Thread object. The method run () is called the Thread body.
The following are several common methods for thread construction:
Public Thread ()
Public Thread (Runnable target)
Public Thread (Runnable target, String name)
Public Thread (String name)
The target parameter is an instance that implements the Runnable interface. It is used to implement the run () method of the thread body. The target can be null, indicating that the thread is executed by the instance itself. The name parameter specifies the thread name, but no constructor is specified. The thread name is allocated by the JVM. For example, the JVM specifies the thread-1 and thread-2 names.
1. method 1 for implementing thread bodies in Java
There are two methods to implement the Thread body in Java: one is to inherit the Thread class Thread, and the other is to implement the interface Runnable. Next, let's take a look at the inherited Thread class Thread method.
If there are 1st methods, it inherits the Thread class Thread and overwrites the method run (). When initializing this class instance, the target can be null, indicates that the thread body is executed by this instance. Because Java only supports single-re-inheritance, classes defined using this method cannot inherit other parent classes, such as the code list Copy codeThe Code is 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. Pipeline signorecase ("1 ")){
// Thread. stop ();
Thread. flag = false;
}
} Catch (IOException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
}

In the main method, create a sub-thread through new textThread () and Use thread. start () method promoter thread. The main method is located in the main thread, and the main thread is responsible for managing other subthreads. The relationship between the process, main thread, and sub-thread in this example.
After the sub-thread starts, it starts to call the run () method. run () is a thread body. Here we write code to implement the processing in the sub-thread. In this case, the sub-thread has to do the following: Sleep for 1 s, the timer is incremented by 1, and then executed repeatedly. Thread. currentThread (). sleep (1000) is sleep for 1 s.
To stop a thread, we added an identifier to the main thread by entering a character in the console.
"1" to change the identifier t1.isRunning = false to end this thread.

Note::
In fact, there is a stop () method in the thread that can also stop the thread, but this method will cause a thread deadlock problem, so it has been abolished in the new JDK version, the alternative solution is to add the logo, which is the solution we used in this example.
  Many people think that threads are hard to understand and there are two main problems.:
The thread sleep. Since the thread has been sleep, can the program run faster?
Generally, the thread body carries out an endless loop. Since the thread has an endless loop, the program should die and no response will be made.
  1. Thread sleep
Readers who have a headache with thread sleep are still using the single-threaded thinking mode. In most cases, our PCs are single CPUs, and only one thread can run at a certain time point. The so-called multithreading means that multiple threads are executed in turn as if they were running at the same time. Therefore, to sleep the current thread, you can hand over the control of the CPU so that other threads have the opportunity to run. Only the alternate running efficiency among multiple threads is the highest. This is like driving through the crossroads, only when I wait, let you go first, and then let him go first can we ensure the highest efficiency. Otherwise, the traffic system will crash and the thread situation will be the same. Therefore, thread sleep is the most effective method for running programs in multiple threads.
  2. Thread dead loop issues
In a single thread, if it is an endless loop, the program should die and have no response, but the endless loop in the thread body (run method) in multithreading can ensure that the thread runs continuously, if the thread is not recycled, the Operation stops once. In the preceding example, the thread runs an endless loop, which can ensure that the thread runs continuously. Every time it runs, it sleeps for 1 s, then wakes up, and then outputs the time information to the console. Therefore, the dead loop of threads is the premise to ensure that the sub-threads are always running. Because it is a sub-thread, it will not block the main thread, and it will not feel the program is dead. However, it is worth noting that sometimes we DO execute a thread body once, so we do not need to loop.
After the program runs, start the thread. After the thread starts, it calculates the elapsed time and outputs the result to the console every 1 s. When one character is entered, the thread stops and the program stops ..

Method 2 for implementing thread bodies in Java
The preceding section describes how to inherit the Thread to implement the Thread body. The following describes another method. This method provides a class that implements the interface Runnable as the target object of a Thread, there are two constructor methods with the Runnable target parameter when constructing a thread:
Thread (Runnable target );
Thread (Runnable target, String name ).
The target is the Thread target object, which is a class that implements Runnable. when constructing the Thread class, the target object (class that implements Runnable) is passed to the Thread instance, the thread body run () method is provided by the target object (class implementing Runnable. At this time, the class implementing interface Runnable can still inherit other parent classes.
See the code list. This is a Java AWT form application.Copy codeThe Code is 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 startup ");
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 actionreceivmed (ActionEvent e ){
IsRunning = false;
}
@ Override
Public void run (){
// TODO Auto-generated method stub
Try {
While (isRunning ){
Thread. currentThread (). sleep (1000 );
Timer ++;
Label. setText ("lost" + 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 read relevant books by themselves. In this example, the application that constructs an AWT form inherits the Frame class. It is not allowed to implement the Thread body using the inheritance method. Because Java is a single inheritance, this class cannot inherit both Frame and Thread. The Runnable interface should be implemented in 2nd ways. The Runnable interface also has a run () method, which implements the thread body method, and its code processing is the same as that in the previous section. Note that in the 2nd methods, a Thread member variable clockThread is created before a Thread object is created using the constructor new Thread (this, the constructor used to create a Thread is Thread (Runnable target), where this represents the current instance, and it is an implementation class that implements the Runnable interface.
Program running result. When the screen starts loading, the thread starts to calculate the time, and the UI is updated once every 1 s. When the "End Time" button is clicked, the timer is stopped.

Method 3 of implementing thread bodies in Java
Thread body Mode 3 is a variant of thread body Mode 2. In essence, thread body Mode 2 is implemented, but 3rd is often used in Android application development. Next we will look at the timer code list of the 3rd methods.Copy codeThe Code is 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 ("timer starts... ");
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 ("expired:" + timer );
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
}
});
ClockThread. start ();
IsRunning = true;
}
@ Override
Public void actionreceivmed (ActionEvent e ){
IsRunning = false;
}
/**
* @ Param args
*/
Public static void main (String [] args ){
TextThread3 thread3 = new TextThread3 ();
}
}

Compared with the 2nd method, we found that the Frame class no longer implements the Runnable interface, but defines an anonymous internal class that implements the Runnable interface when instantiating the Thread class:Copy codeThe Code is as follows: clockThread = new Thread (new Runnable (){
@ Override
Public void run (){
While (isRunning ){
Try {
Thread. currentThread (). sleep (1000 );
Timer ++;
Label. setText ("expired:" + timer );
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
}
});

There are still many content related to Java multithreading, such as thread priority and thread synchronization. Since these content is not closely related to this book, I will not introduce it any more, for other thread knowledge, refer to Java books. Next we will introduce the threads in Android.
Threads in Android
Multithreading is widely used on the Android platform, and multithreading is required in terms of UI update, game development, and time-consuming processing (network communication, etc. Android threads involve Handler, Message, MessageQueue, logoff, and HandlerThread.
  Android thread application problems and Analysis
To introduce these concepts, we transplanted the timer case to the Android system and modified the code list in Frame mode.Copy codeThe Code is 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 (Message msg ){
Switch (msg. what ){
Case 0:
MTextView. setText ("expired:" + 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 ("expired:" + timer );
}
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
});
MThread. start ();
}
}

An exception occurred when running the program package ,.

Open the LogCat window, error log information.

The exception message thrown by the system is "Only the original thread that created a view hierarchy can touch its views". In Android, UI update must be updated by the thread that created it, but cannot be updated in other threads. This is the reason for the above error.
Now let's analyze the above case. There are two threads in the above program: one main thread and one subthread, their responsibilities.
Because labelTimer is a UI control, it is created in the main thread, but it is updated in the Child thread. The update operation is implemented in the run () method of the clockThread thread, the Code is as follows:
Copy codeThe Code is 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 ("expired:" + timer );
}
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
});

This process violates the multi-thread programming rules of Android, and the system will throw an exception "Only the original thread that created a view hierarchy can touch its views ".
To solve this problem, we must clarify the main thread and sub-thread responsibilities. The main thread is responsible for creating, displaying, and updating UI controls, processing UI events, starting threads, and stopping subthreads; the subthread is responsible for calculating the elapsed time and sending an update UI message to the main thread, rather than directly updating the UI.
The main thread is responsible for displaying UI controls, processing UI events, starting threads, stopping subthreads, and updating UIS. The subthread is responsible for calculating the elapsed time and sending an update UI message to the main thread. But new problems have emerged: How do subthreads send messages and communicate with the main thread?
In Android, a thread has two objects: Message and MessageQueue, which can implement inter-thread communication. Next let's take a look at the modified code list.Copy codeThe Code is 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 (Message msg ){
Switch (msg. what ){
Case 0:
MTextView. setText ("expired:" + 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, to make the Android code more compact, write the thread creation and startup in a statement, as shown belowCopy codeThe Code is 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 ();

The result of running the simulator is 8-1. The timer starts immediately after the screen is loaded. You can also click "Stop timer" 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.